gpt4 book ai didi

Golang 嵌入式结构

转载 作者:IT王子 更新时间:2023-10-29 02:28:17 31 4
gpt4 key购买 nike

我对 Go 在嵌入式结构中关于变量“覆盖”的行为感到有点困惑。

第一种情况如果 child 结构嵌入了一个包含字段 Attrparent 结构,我可以使用 child.Attr< 无差别地访问 Attr 的值child.parent.Attr。这是一个 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)
}

第二种情况但是,如果子结构本身包含一个名为 Attr 的字段,那么这两个字段是不同的并且可以单独访问,如下所示 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)
}

我很惊讶 golang 中允许这种隐式行为。我原以为语言会更严格,因为它在很多方面都如此。此外,我找不到关于此的明确规范。这只是副作用还是我可以使用该功能?

最佳答案

Golang 规范实际上说明了嵌入字段是如何解析的

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.

然后...

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.

关于Golang 嵌入式结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56234132/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com