Go語言中struct的匿名屬性特征實例分析
更新時間:2015年02月08日 11:42:28 作者:books1958
這篇文章主要介紹了Go語言中struct的匿名屬性特征,實例分析了struct的匿名屬性特征,對于深入學習Go語言程序設計具有一定參考借鑒價值,需要的朋友可以參考下
本文實例分析了Go語言中struct的匿名屬性特征。分享給大家供大家參考。具體分析如下:
Go語言中struct的屬性可以沒有名字而只有類型,使用時類型即為屬性名。(因此,一個struct中同一個類型的匿名屬性只能有一個)
復制代碼 代碼如下:
type PersonC struct {
id int
country string
}
//匿名屬性
type Worker struct {
//如果Worker有屬性id,則worker.id表示W(wǎng)orker對象的id
//如果Worker沒有屬性id,則worker.id表示W(wǎng)orker對象中的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
*/
}
id int
country string
}
//匿名屬性
type Worker struct {
//如果Worker有屬性id,則worker.id表示W(wǎng)orker對象的id
//如果Worker沒有屬性id,則worker.id表示W(wǎng)orker對象中的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
*/
}
希望本文所述對大家的Go語言程序設計有所幫助。
相關文章
GO語言創(chuàng)建錢包并遍歷錢包(wallet)的實現(xiàn)代碼
比特幣錢包實際上是一個密鑰對,當你安裝 一個錢包應用,或者是使用一個比特幣客戶端來生成一個新地址是,他就會為你生成一個密鑰對,今天通過本文給大家分享go語言遍歷錢包的相關知識,一起看看吧2021-05-05Go語言使用protojson庫實現(xiàn)Protocol Buffers與JSON轉換
本文主要介紹Google開源的工具庫Protojson庫如何Protocol Buffers與JSON進行轉換,以及和標準庫encoding/json的性能對比,需要的朋友可以參考下2023-09-09使用Go語言創(chuàng)建WebSocket服務的實現(xiàn)示例
這篇文章主要介紹了使用Go語言創(chuàng)建WebSocket服務的實現(xiàn)示例,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2020-03-03