当前位置: 移动技术网 > IT编程>脚本编程>Go语言 > Go语言中struct的匿名属性特征实例分析

Go语言中struct的匿名属性特征实例分析

2017年12月08日  | 移动技术网IT编程  | 我要评论

本文实例分析了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语言程序设计有所帮助。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网