2017-07-26 23 views
0

有没有在手边复制内部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} 
+1

[Golang可能的重复:是否可以在不同的结构类型之间进行转换?](https://stackoverflow.com/questions/24613271/golang -is-conversion-between-different-struct-types-possible) –

+1

你不能使用。 box:= rated.Box ?? –

+0

也有关:https://stackoverflow.com/a/37725577/19020 –

回答

5

Embedding一个结构体的类型添加一个字段,在结构,并且可以使用非限定类型名称引用它(不合格手段省略包名和可选指针标志)。

例如:

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) 

输出:

*main.Box &{Name:foo} 
+3

Go是不是以C++或Java相同的方式面向对象。对于需要多态的情况,您应该使用接口。没有他们,这个答案是最好的。 –