本文实例分析了go语言中struct匿名属性特征。分享给大家供大家参考。具体分析如下:

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 

    */ 

}

希望本文所述对大家的Go语言程序设计有所帮助。

声明:本站(华域联盟www.cnhackhy.com)所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。