Go 向下投射较高类型到较低类型
除了手动复制内部Go 向下投射较高类型到较低类型,go,struct,type-conversion,embedding,Go,Struct,Type Conversion,Embedding,除了手动复制内部框值外,是否还有语言功能将RatedBox向下转换到框 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 } 结构中的类型向结构添加一个
框
值外,是否还有语言功能将RatedBox
向下转换到框
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
}
结构中的类型向结构添加一个字段,您可以使用非限定类型名称来引用它(非限定意味着省略包名称和可选指针符号)
例如:
box := rated.Box
fmt.Printf("%T %+v", box, box)
输出(在上尝试):
请注意,复制值,因此框
局部变量将保存RatedBox.box
字段值的副本。如果希望它们“相同”(指向相同的框
值),请使用指针,例如:
box := &rated.Box
fmt.Printf("%T %+v", box, box)
当然,这里的box
类型将是*box
或者,您可以选择嵌入指针类型:
type RatedBox struct {
*Box
Points int
}
然后(在电脑上试用):
最后2次的输出:
*main.Box &{Name:foo}
与C++或java一样,GO不是面向对象的。对于需要多态性的情况,应该使用接口。这个答案是你在没有它们的情况下能做的最好的答案。你不能使用的可能的副本。box:=额定值.box??同样相关:@DanEsparza我看不出我的问题怎么可能是重复的
type RatedBox struct {
*Box
Points int
}
rated := RatedBox{Box: &Box{Name: "foo"}, Points: 10}
box := rated.Box
fmt.Printf("%T %+v", box, box)
*main.Box &{Name:foo}