九、struct
定义自己的类型
type foo int
struct
1 package main 2 3 import "fmt" 4 5 type Skills []string 6 7 type Human struct { 8 name string 9 age int 10 weight int 11 } 12 13 type Student struct { 14 Human // 匿名字段,struct 15 Skills // 匿名字段,自定义的类型string slice 16 int // 内置类型作为匿名字段 17 speciality string 18 } 19 20 func main() { 21 // 初始化学生Jane 22 jane := Student{Human: Human{"Jane", 35, 100}, speciality: "Biology"} 23 // 现在我们来访问相应的字段 24 fmt.Println("Her name is ", jane.name) 25 fmt.Println("Her age is ", jane.age) 26 fmt.Println("Her weight is ", jane.weight) 27 fmt.Println("Her speciality is ", jane.speciality) 28 // 我们来修改他的skill技能字段 29 jane.Skills = []string{"anatomy"} 30 fmt.Println("Her skills are ", jane.Skills) 31 fmt.Println("She acquired two new ones ") 32 jane.Skills = append(jane.Skills, "physics", "golang") 33 fmt.Println("Her skills now are ", jane.Skills) 34 // 修改匿名内置类型字段 35 jane.int = 3 36 fmt.Println("Her preferred number is", jane.int) 37 }
结果:
Her name is Jane
Her age is 35
Her weight is 100
Her speciality is Biology
Her skills are [anatomy]
She acquired two new ones
Her skills now are [anatomy physics golang]
Her preferred number is 3
 
                    
                     
                    
                 
                    
                 
 
                
            
         
         浙公网安备 33010602011771号
浙公网安备 33010602011771号