go中的匿名变量

在结构体B中使用匿名成员A,相当于在B中定义了A的所有变量和函数

type A struct{
	dataA int
}

func (this *A)foo(){
	fmt.Print("i am A")
}

type B struct {
	A
}

//============
//实际上相当于
type B struct{
	dataA int
}

func (this *B)foo(){
	fmt.Print("i am A")
}
//============

//那么在使用时直接使用A中的数据即可
func main(){
	b := B{A{10}}
	fmt.Print(b.dataA)
}

若不适用匿名对象,则使用A的变量时需要通过A成员调用,即多了一层间接层

type A struct{
	dataA int
}

func (this *A)foo(){
	fmt.Print("i am A")
}

type B struct {
	a A
}

func main(){
	b := B{A{10}}
	fmt.Print(b.a.dataA)//只能通过a调用
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章