Embedding

The Little Go Book http://openmymind.net/The-Little-Go-Book/ 里面介绍了 Embedding 的实现方法,

示例程序如下(有修改):

package main

import "fmt"

type Person struct {
	Name string
}

func (p *Person) Introduce() {
	fmt.Println("Hi, I'm", p.Name)
}

type Saiyan struct {
	*Person
	Power int
}

func main() {
	goku := new(Saiyan)
	goku.Person = new(Person) // 必须先有 Person
	goku.Name = "Goku"        // 然后才有 Name
	goku.Power = 9001
	goku.Introduce()
}

  

其中,特别需要注意的是,虽然 goku 可以“免费”获得 Person 的全部能力(比如 .Name 和 .Introduce() ),但前提是必须先给 goku.Person 赋值。如果删掉那句 goku.Person = new(Person) 

即,变成这样:

func main() {
	goku := new(Saiyan)

	goku.Name = "Goku" // 此时,还没有 goku.Name
	goku.Power = 9001
	goku.Introduce()
}

  那么,就会产生 panic: runtime error

 

posted @ 2017-04-09 23:53  AHUI-2017  阅读(174)  评论(0编辑  收藏  举报