2017-07-26 21 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相同的方式面向對象。對於需要多態的情況,您應該使用接口。沒有他們,這個答案是最好的。 –