duangua5742 2019-05-21 08:25
浏览 27
已采纳

Golang嵌入式结构

I am a little confused with a behavior of Go regarding variable 'overriding' in embedded structure.

First situation If a child structure embeds a parent structure containing a field Attr, I can access the value of Attr indifferently with child.Attr or child.parent.Attr. Here is an example :

package main

import (
    "fmt"
    "encoding/json"
)

type parent struct {
    Attr    int `json:"attr"`
}

type child struct {
    parent
}

func main() {
    var c child
    json.Unmarshal([]byte(`{"i": 1}`), &c)
    fmt.Println(c.Attr)
    fmt.Println(c.parent.Attr)
}

Second situation However, if the child structure contains itself a field named Attr, those two fields are different and can be accessed separately, as shows the following example :

package main

import (
    "fmt"
    "encoding/json"
)

type parent struct {
    Attr    int `json:"attr"`
}

type child struct {
    parent
    Attr    int
}

func main() {
    var c child
    json.Unmarshal([]byte(`{"attr": 1}`), &c)
    fmt.Println(c.Attr)
    fmt.Println(c.parent.Attr)
}

I am very surprised that this implicit behavior is allowed in golang. I would have expected the language to be stricter as it is on so many points. Besides, I wasn't able to find a clear specification about this. Is it just a side-effect or can I use that feature?

  • 写回答

1条回答 默认 最新

  • douzuo0002 2019-05-21 09:10
    关注

    Golang specification actually states how embedded fields are resolved

    A selector f may denote a field or method f of a type T, or it may refer to a field or method f of a nested embedded field of T. The number of embedded fields traversed to reach f is called its depth in T. The depth of a field or method f declared in T is zero. The depth of a field or method f declared in an embedded field A in T is the depth of f in A plus one.

    Then...

    For a value x of type T or *T where T is not a pointer or interface type, x.f denotes the field or method at the shallowest depth in T where there is such an f. If there is not exactly one f with shallowest depth, the selector expression is illegal.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 请问读取环境变量文件失败是什么原因?
  • ¥15 在若依框架下实现人脸识别
  • ¥15 网络科学导论,网络控制
  • ¥100 安卓tv程序连接SQLSERVER2008问题
  • ¥15 利用Sentinel-2和Landsat8做一个水库的长时序NDVI的对比,为什么Snetinel-2计算的结果最小值特别小,而Lansat8就很平均
  • ¥15 metadata提取的PDF元数据,如何转换为一个Excel
  • ¥15 关于arduino编程toCharArray()函数的使用
  • ¥100 vc++混合CEF采用CLR方式编译报错
  • ¥15 coze 的插件输入飞书多维表格 app_token 后一直显示错误,如何解决?
  • ¥15 vite+vue3+plyr播放本地public文件夹下视频无法加载