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
mark.Human = Human{"a", 55, 220} mark.Human.age -= 1
3.method
type Rect struct { x, y float64 width, height float64 }//method
func (r ReciverType) funcName(params) (results) {}
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) }