Go-匿名字段

package main

import “fmt”

type Base struct {
Name string
Age int
}

func (b * Base) Test() {
fmt.Println(“test successfully”)
}

type Child struct {
Base // 匿名字段, 默认把Base的所有字段都继承过来了。 这样看起来才像真正的继承
Age int
}

func main() {
c := new(Child)
c.Name = “hello” // 可以直接使用Base中的字段
c.Age = 20 // 如果有重复的, 则最外的优先

fmt.Println(c.Name)     // hello
fmt.Println(c.Age)      // 20
fmt.Println(c.Base.Age) // 要访问Base中的,可以这样写 0
c.Test()

}
go语言中的”继承“并不是真正的意义上的继承,确切地说是组合。匿名字段让习惯了C++/java之类的程序员用go更加得心应手。
作为一门年轻的语言,不得不说go语言对程序员还是非常友好的.