将较高类型向下转换为较低类型

downcast higher-type to lower

除了手动复制内部 Box 值之外,是否有语言功能将 RatedBox 向下转换为 Box

type Box struct {
    Name string
}

type RatedBox struct {
    Box
    Points int
}

func main() {
    rated := RatedBox{Box: Box{Name: "foo"}, Points: 10}

    box := Box(rated) // does not work
}

go-playground

// works, but is quite verbose for structs with more members
box := Box{Name: rated.Name}

Embeddingstruct中的类型在struct中添加一个字段,可以使用非限定类型名来引用它(非限定表示省略包名和可选的指针符号)。

例如:

box := rated.Box
fmt.Printf("%T %+v", box, box)

输出(在 Go Playground 上尝试):

main.Box {Name:foo}

请注意,assignment 复制值,因此 box 局部变量将保存 RatedBox.Box 字段值的副本。如果您希望它们成为 "same"(指向相同的 Box 值),请使用指针,例如:

box := &rated.Box
fmt.Printf("%T %+v", box, box)

但是这里 box 的类型当然是 *Box.

或者您可以选择嵌入指针类型:

type RatedBox struct {
    *Box
    Points int
}

然后(在 Go Playground 上尝试):

rated := RatedBox{Box: &Box{Name: "foo"}, Points: 10}

box := rated.Box
fmt.Printf("%T %+v", box, box)

最后2个输出:

*main.Box &{Name:foo}