go结构体创建的六种方式

package main

import "fmt"

type Teacher struct {
   Name   string
   Age    int8
   School string
   Sex    string
}

func main() {
   //方式一
   var t1 Teacher
   fmt.Println(t1)
   t1.Name = "张老师"
   t1.Age = 38
   t1.School = "家里蹲大学"
   t1.Sex = "男"
   fmt.Println(t1)
   //方式二

   var t2 Teacher = Teacher{}
   fmt.Println(t2)
   //方式三
   var t3 Teacher = Teacher{"张老师", 30, "家里蹲大学", "男"}
   fmt.Println(t3)
   //方式四 通过键值对赋值,不用完全填空每个属性
   var t4 Teacher = Teacher{Name: "张老师",
      Age:    30,
      School: "家里蹲大学"}
   fmt.Println(t4)
   //方式五 通过new 和结构体类型生成 指针
   var t5 *Teacher = new(Teacher)
   (*t5).Name = "猫老师"
   fmt.Println(*t5)
   //方式六 通过 & 和结构体类型生成 指针 可以在{}填充字段,如果不是键值对需要填充完整
   var t6 *Teacher = &Teacher{"猫老师", 23, "家里蹲大学", "男"}

   fmt.Println(*t6)
}

你可能感兴趣的:(golang,golang,开发语言,后端)