funcmain() { // 1-struct as a value type:值类型 变量本身 var pers1 Person pers1.firstName = "Chris" pers1.lastName = "Woodward" upPerson(&pers1) fmt.Printf("The name of the person is %s %s\n", pers1.firstName, pers1.lastName)
// 2—struct as a pointer:使用new返回的是指向已分配内存的指针 pers2 := new(Person) pers2.firstName = "Chris" pers2.lastName = "Woodward" (*pers2).lastName = "Woodward" pers2.lastName = "Woodward"//指针类型可以不解引用 直接访问子元素 upPerson(pers2) fmt.Printf("The name of the person is %s %s\n", pers2.firstName, pers2.lastName)
// 3—struct as a literal:结构体字面量 混合字面量语法是一种简写,底层任然会调用new 因此返回的仍然是内存指针 pers3 := &Person{"Chris","Woodward"} upPerson(pers3) fmt.Printf("The name of the person is %s %s\n", pers3.firstName, pers3.lastName) }
输出:
1 2 3
The name of the person is CHRIS WOODWARD The name of the person is CHRIS WOODWARD The name of the person is CHRIS WOODWARD
type Node struct{//链表定义 data int next *Node } type treeNode struct{//树节点定义 le *treeNode ri *treeNode data value }
结构体工厂
1 2 3 4 5 6 7 8 9 10 11 12 13
type File struct{//定义一个结构体file fd int name string } funcNewFile(fd int, name string) *File{//结构体创建工厂方法 if fd<0{ returnnil } return &File(fd, name)//输入参数 返回一个指向结构体实例的指针 } f := NewFile(100,"./zibu.txt") //调用工厂方法 size := unsafe.Sizeof(T{})
type TagType struct { // tags field1 bool"An important answer" field2 string"The name of the thing" field3 int"How much there are" } funcmain() { tt := TagType{true, "Barak Obama", 1} for i := 0; i < 3; i++ { refTag(tt, i) } }