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調用
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章