Go語言中struct的屬性可以沒有名字而隻有類型,使用時類型即為屬性名。(是以,一個struct中同一個類型的匿名屬性隻能有一個)
type PersonC struct {
id int
country string
}
//匿名屬性
type Worker struct {
//如果Worker有屬性id,則worker.id表示Worker對象的id
//如果Worker沒有屬性id,則worker.id表示Worker對象中的PersonC的id
id int
name string
int
*PersonC
}
func structTest0404() {
w := &Worker{}
w.id = 201
w.name = "Smith"
w.int = 49
w.PersonC = &PersonC{100001, "China"}
fmt.Printf("name:%s,int:%d\n", w.name, w.int)
fmt.Printf("inner PersonC,id:%d,country:%s\n",
w.PersonC.id, w.PersonC.country)
fmt.Printf("worker.id:%d,personC.id:%d\n", w.id, w.PersonC.id)
/*output:
name:Smith,int:49
inner PersonC,id:100001,country:China
worker.id:201,personC.id:100001
*/
}