gpt4 book ai didi

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

转载 作者:IT王子 更新时间:2023-10-29 01:56:19 24 4
gpt4 key购买 nike

下面的代码是 Embedded Struct 或 Nested 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)
}

最佳答案

spec将其称为嵌入字段:

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

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

我不确定您所说的“在另一种结构类型中使用一种结构类型”是什么意思,但是您通过将一种结构类型嵌入另一种结构类型来在 secretAgent 中使用 person .在大多数情况下,person 字段也被提升为表现得像 secretAgent 的成员:

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

所以你可以说:

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

sa1.first

但不是:

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

您还可以通过 person 显式引用嵌入的 person 字段:

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

关于go - 嵌入式结构还是嵌套结构?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55768675/

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