Golang学习笔记(六):struct
struct
struct,一组字段的集合,类似其他语言的class
放弃了大量包括继承在内的面向对象特性,只保留了组合(composition)这个最基础的特性
1.声明及初始化
type person struct { name string age int }//初始化
func main() { var P person
P.name = "tom" P.age = 25 fmt.Println(P.name)
P1 := person{"Tom1", 25} fmt.Println(P1.name)
P2 := person{age: 24, name: "Tom"} fmt.Println(P2.name) }
2.struct的匿名字段(继承)
type Human struct { name string age int weight int }tyep Student struct { Human //匿名字段,默认Student包含了Human的所有字段 speciality string }
mark := Student(Human{"mark", 25, 120}, "Computer Science")
mark.name mark.age
能够实现字段继承,当字段名重复的时候,优先取外层的,可以通过指定struct名还决定取哪个
mark.Human = Human{"a", 55, 220} mark.Human.age -= 1
struct不仅可以使用struct作为匿名字段,自定义类型、内置类型都可以作为匿名字段,而且可以在相应字段上做函数操作
3.method
type Rect struct { x, y float64 width, height float64 }//method
Reciver 默认以值传递,而非引用传递,还可以是指针
指针作为Receiver会对实例对象的内容发生操作,而普通类型作为Receiver仅仅是以副本作为操作对象,而不对原实例对象发生操作
func (r ReciverType) funcName(params) (results) {}
如果一个method的receiver是*T,调用时,可以传递一个T类型的实例变量V,而不必用&V去调用这个method
func (r *Rect) Area() float64 { return r.width * r.height }func (b *Box) SetColor(c Color) { b.color = c }
4.method继承和重写
采用组合的方式实现继承
type Human struct { name string }type Student struct { Human School string }
func (h *Human) SayHi() { fmt.Println(h.name) }
//则Student和Employee的实例可以调用 func main() { h := Human{name: "human"} fmt.Print(h.name) h.SayHi()
s := Student{Human{"student"}} s.SayHi()
}
还可以进行方法重写
funct (e *Student) SayHi() { e.Human.SayHi() fmt.Println(e.School) }