小编Nic*_*ier的帖子

Golang 嵌入式结构

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

第一种情况 如果一个child结构嵌入了一个parent包含字段的结构,我可以使用orAttr访问 Attr 的值。这是一个例子child.Attrchild.parent.Attr

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)
}
Run Code Online (Sandbox Code Playgroud)

第二种情况 但是,如果子结构本身包含一个名为 的字段Attr,则这两个字段是不同的,可以单独访问,如下所示:

package main

import (
    "fmt"
    "encoding/json"
)

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

type child struct {
    parent
    Attr    int
} …
Run Code Online (Sandbox Code Playgroud)

go

1
推荐指数
1
解决办法
542
查看次数

标签 统计

go ×1