Go 结构体的匿名字段
package main
import "fmt"
//结构体的匿名字段
/*
匿名结构体和匿名字段:
匿名结构体: 没有名字的结构体,
在创建匿名结构体时,同时创建对象
变量名 := struct{
定义字段Feild
}
匿名字段: 一个结构体的字段没有字段名
匿名函数:
*/
func main() {
s1 := Student{name:"张三",age:21}
fmt.Println(s1.name,s1.age)
//匿名函数
func(){
fmt.Println("hello world")
}()
//匿名结构体
s2 := struct {
name string
age int
}{
name:"李四",
age: 22,
}
fmt.Println(s2.name,s2.age)
w1 := Worker{"狗子",21}
fmt.Println(w1) //{狗子 21}
fmt.Println(w1.string,w1.int) //狗子 21
}
type Worker struct {
string //匿名字段
int //匿名字段,默认使用数据类型作为名字,匿名字段的类型不能重复,否则会冲突
}
type Student struct {
name string
age int
}
结果:
张三 21
hello world
李四 22
{狗子 21}
狗子 21