2016-10-27 59 views
1

我正在嘗試將結構複製到另一個實現接口的結構中。我的代碼如下:將一個結構複製到一個實現接口的結構中

 package main 

    import (
     "fmt" 
    ) 

    type intf interface { 
     SaySomething(string) 
     LaunchTheDevice(origin) 
    } 

    type destination struct{ 
     origin 
    } 

    func (dest *destination) SaySomething(s string) { 
     fmt.Println("I'm saying --> ",s) 
    } 

    func (dest *destination) LaunchTheDevice(theOrigin origin) { 
     *dest = theOrigin 
    } 

    type origin struct{ 
     name string 
     value string 
     infos string 
    } 

    func main() { 
     firstValue:= new(origin) 
     firstValue.name = "Nyan" 
     firstValue.value = "I'm the only one" 
     firstValue.infos = "I'm a cat" 

     secondValue := new(destination) 
     secondValue.LaunchTheDevice(*firstValue) 
    } 

我想要的功能LaunchTheDevice()設置的destination值。但是當我運行我的代碼時,出現此錯誤:

cannot use theOrigin (type origin) as type destination in assignment 

那麼我該如何做到這一點?爲什麼我不能運行我的代碼?我不明白,因爲我可以輸入

dest.name = "a value" 
dest.value = "another value" 
dest.infos = "another value" 

dest=theOrigindest具有相同的結構作爲theOrigin不起作用。

在此先感謝!

+3

'dest.origin = theOrigin' – thwd

回答

3

該字段origin是嵌入式字段。應用程序可以使用以下代碼設置字段:

func (dest *destination) LaunchTheDevice(theOrigin origin) { 
    dest.origin = theOrigin 
} 

嵌入字段的名稱與類型名稱相同。