go struct

第一种初始化方法:

package main

import (
	"fmt"
)

type person struct {
	Name string
	Age  int
}

func main() {
	a := person{}
	a.Name = "wang"
	a.Age = 20
	fmt.Println(a)
}

第二种初始化方法:

package main

import (
	"fmt"
)

type person struct {
	Name string
	Age  int
}

func main() {
	a := person{
		Name: "wang",
		Age:  22,
	}
	fmt.Println(a)
}

第三种初始化方法:(匿名结构)

package main

import (
	"fmt"
)

func main() {
	a := struct {
		Name string
		Age  int
	}{
		Name: "wang",
		Age:  22,
	}
	fmt.Println(a)
}

嵌套匿名结构

package main

import (
	"fmt"
)

type person struct {
	Name    string
	Age     int
	//Contact 为匿名结构
	Contact struct {
		Phone, City string
	}
}

func main() {
	a := person{Name: "wang", Age: 19}
	//Contact 为匿名结构,只能按照如下方法初始化
	a.Contact.City = "bj"
	a.Contact.Phone = "111"
	fmt.Println(a)
}

注意: struct 为值类型, 所以在定义的时候,加上 & 符号,便于修改 struct 中内容, 如

	a := &person{
			Name string  
			Age int
		}{
			Name: "wang", 
			Age: 22,
		}

匿名字段

package main

import (
	"fmt"
)

type person struct {
	string
	int
}

func main() {
	a := person{"wang", 19}
	fmt.Println(a)
}

相互赋值/比较

package main

import (
	"fmt"
)

type person struct {
	string
	int
}


func main() {
	a := person{"wang", 19}
	b := person{"wang", 19}
	c := a
	// 注意 必须 类型相同才能比较
	fmt.Println(a == b)
	fmt.Println(c)
}

匿名嵌入结构

package main

import (
	"fmt"
)

type human struct {
	sex int
}

type student struct {
	//匿名嵌入结构,默认把human当作key名
	human
	Name string
	Age  int
}

func main() {
	a := student{Name: "wang", Age: 19, human: human{sex: 0}}

	fmt.Println(a)
}

结构体嵌套字段取值

package main

import (
	"fmt"
)

type A struct {
	Name string
}

type B struct {
	A
}

func main() {
	b := B{A: A{Name: "wang"}}

	fmt.Println(b.Name, b.A.Name)
}