duanfu1945 2019-04-19 22:54
浏览 95

嵌入式结构还是嵌套结构?

Is the following code is an example of Embedded Struct or Nested Struct or something else? And Are we using one struct type (person) in another type struct (secretAgent) ?

package main

import "fmt"

type person struct {
    first string
    last  string
    age   int
}

type secretAgent struct {
    person
    ltk bool
}

func main() {

    sa1 := secretAgent{
        person: person{
            first: "James",
            last:  "Bond",
            age:   32,
        },
        ltk: true,
    }

    fmt.Println(sa1.first, sa1.last, sa1.age, sa1.ltk)
}
  • 写回答

2条回答 默认 最新

  • dsqtl335227 2019-04-19 23:37
    关注

    The spec refers to that as an embedded field:

    A field declared with a type but no explicit field name is called an embedded field. [...]

    struct {
        T1        // field name is T1
        ...
    }
    

    I'm not sure what you mean by "using one struct type in another struct type" but you are using person inside secretAgent by embedding one struct type inside another. The person fields are also promoted to behave like members of secretAgent in most cases:

    Promoted fields act like ordinary fields of a struct except that they cannot be used as field names in composite literals of the struct.

    So you can say:

    sa1 := secretAgent{
        person: person{
            first: "James",
            last:  "Bond",
            age:   32,
        },
        ltk: true,
    }
    

    and

    sa1.first
    

    but not:

    sa1 := secretAgent{
        first: "James",
        last:  "Bond",
        age:   32,
        ltk: true,
    }
    

    You can also explicitly refer to the embedded person fields through the person:

    // As a promoted field...
    sa1.first
    // More explicitly...
    sa1.person.first
    
    评论

报告相同问题?

悬赏问题

  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算