【问题标题】:downcast higher-type to lower向下看高型到低
【发布时间】:2017-07-26 13:14:22
【问题描述】:

除了手动复制内部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}

【问题讨论】:

标签: go struct type-conversion embedding


【解决方案1】:

Embedding struct 中的类型会在 struct 中添加一个字段,您可以使用不合格的类型名称来引用它(不合格意味着省略包名和可选的指针符号)。

例如:

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

输出(在Go Playground上试试):

main.Box {Name:foo}

注意assignment 复制了值,所以box 局部变量将保存RatedBox.Box 字段值的副本。如果您希望它们“相同”(指向相同的 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}

【讨论】:

  • Go 不像 C++ 或 Java 那样面向对象。对于需要多态性的情况,您应该使用接口。这个答案是没有它们你能做的最好的。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-03-19
  • 2020-08-10
  • 1970-01-01
  • 2020-02-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多