gpt4 book ai didi

Go:嵌入类型在派生类型中的字段初始化

转载 作者:IT王子 更新时间:2023-10-29 01:51:18 26 4
gpt4 key购买 nike

这是有效的代码:

package main

import (
"fmt"
)

type Base struct {
Field int
}

type Derived struct {
Base
}

func main() {
d := &Derived{}
d.Field = 10
fmt.Println(d.Field)
}

下面是使用 ./main.go:17: unknown Derived field 'Field' in struct literal 编译失败的代码

package main

import (
"fmt"
)

type Base struct {
Field int
}

type Derived struct {
Base
}

func main() {
d := &Derived{
Field: 10,
}
fmt.Println(d.Field)
}

这里到底发生了什么?很抱歉,如果它很明显,但我就是不明白。

最佳答案

来自语言specification :

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

所以这就是它工作的原因。

这里有两种可能的方法来解决该限制,每种方法都在以下函数中进行了说明:

func main() {
d := &Derived{
Base{Field: 10},
}

e := new(Derived)
e.Field = 20

fmt.Println(d.Field)
fmt.Println(e.Field)
}

关于Go:嵌入类型在派生类型中的字段初始化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32906086/

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