// Person 在Student中成为了匿名字段 // 直接被访问,也叫提升字段 type Person struct { name string age int }
type Student struct { Person // 匿名字段,模拟继承结构 or *Person school string }
type Student struct { person Person // 普通嵌套字段,必须逐层访问 school string } // You can declare a method on non-struct types, too.
// method,会自动关联到对应的struct // non-pointer receiver is not common! please don't use it! func(p Person) getName() { return p.name }
// 指针类型 is used to modify struct variable! // Since methods often need to modify their receiver // pointer receivers are more common than value receivers. func(p *Person) setAge() { p.age = p.age + 10 }
// 或者声明interface 变量 var u Usb // u 不能访问 m 的字段 u = m u.start() u.end()
空接口,没有方法,所以可以认为所有类型都实现了它,可以用作函数的参数去接收任何数据类型。
The main usage of empty interface is func arguments.
1 2 3 4 5 6 7 8 9 10 11 12
type A interface {} // because all type implicitly implements empty interface // so we can use interface{} as var type var a1 A = "hello" var a2 A = 123 var a3 A = true var a4 interface{} = "hello"
// map value存储任意类型 var map1 = make(map[string]interface{}) // slice 存储任意类型 var slice1 = make([]interface{})