Go初始化结构体数组/切片

go语言结构体数组/切片声明和初始化


package main
 
import "fmt"
 
func main() {
 
    var s []student
    fmt.Printf("%T\n", s) //[]main.student
    fmt.Println(s) //[]
    //初始化结构体切片
    s = []student{
        {
            name: "yang",
            age:  18,
        },
    }
    fmt.Println(s) //[{yang 18}]
 
    var s2 [5]student
    fmt.Printf("%T\n", s) //[]main.student
    fmt.Println(s2) //[{ 0} { 0} { 0} { 0} { 0}] //默认值空和零
    //初始化结构体数组
    s2 = [5]student{
        {
            name: "yang",
            age:  18,
        },
    }
    fmt.Println(s2) //[{yang 18} { 0} { 0} { 0} { 0}]
 
}
 
type student struct {
    name string
    age  int
}

你可能感兴趣的:(go)