匿名成员的简介
只声明变量类型而不声明变量名的变量称之为匿名成员
Go语言有一个特性让我们只声明一个成员对应的数据类型而不指名成员的名字;这类成员就叫匿名成员。匿名成员的数据类型必须是命名的类型或指向一个命名的类型的指针。
简单的举例:
type User struct {
string
Id int
}
string
匿名结构体
extends
简单的例子:
package main
import "fmt"
type Car interface {
Start(s string) string
Stop(s string) string
}
type BenzBand struct {
Engine string
Body string
Wheel string
}
type BenzCars struct {
}
func (b BenzCars) Start(s string) string {
return "benz " + s + " is start()"
}
func (b BenzCars) Stop(s string) string {
return "benz " + s + " is stop()"
}
type MyCar struct {
BenzCars
BenzBand
Id string
}
func main() {
mycar := MyCar{
BenzCars: BenzCars{},
BenzBand: BenzBand{Engine: "myengine", Wheel: "mywheel", Body: "mybody"},
Id: "75761",
}
fmt.Println(mycar.Start(mycar.Id), mycar.BenzBand)
}
benz 75761 is start() {myengine mybody mywheel}
匿名接口
匿名接口的优点:
匿名接口的方式不依赖具体实现,可以对任意实现了该接口的类型进行重写。这在写一些公共库时会非常有用.
@Override
简单的例子:
package main
import "fmt"
type Person interface {
State() string
}
type Man struct {
Name string
Age string
}
func (m Man) State() string{
return "Man :\n"+m.Name+"\n"+m.Age+"\n"
}
type MarryMan struct {
Person
}
func (m MarryMan) State() string{
return "Married "+m.Person.State()
}
func GetMarry(person Person) MarryMan{
return MarryMan{person}
}
func main() {
man:= Man{
Name: "tom",
Age: "19",
}
mman:=GetMarry(man)
fmt.Println(man.State())
fmt.Println(mman.State())
}
Man :
tom
19
Married Man :
tom
19