英文:
Copy a struct into a struct which implement an interface
问题
我目前正在尝试将一个结构体复制到另一个实现了接口的结构体中。我的代码如下:
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=theOrigin不起作用,尽管dest和theOrigin具有相同的结构体。
提前感谢!
英文:
I'm currently trying to copy a struct into another structure which implement an interface. My code is the following:
     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)
     }
I want that the function LaunchTheDevice() set the values of destination. But when I run my code I get this error:
cannot use theOrigin (type origin) as type destination in assignment
So how can I do this? And why I can't run my code? I don't understand because I can type
dest.name = "a value"
dest.value = "another value"
dest.infos = "another value"
But dest=theOrigin doesn't work while dest have the same struct as theOrigin.
Thanks in advance!
答案1
得分: 3
字段origin是一个嵌入字段。应用程序可以使用以下代码设置该字段:
func (dest *destination) LaunchTheDevice(theOrigin origin) {
    dest.origin = theOrigin
}
嵌入字段的名称与类型名称相同。
英文:
The field origin is an embedded field. The application can set the field using the following code:
 func (dest *destination) LaunchTheDevice(theOrigin origin) {
    dest.origin = theOrigin
 }
The name of an embedded field is the same as the type name.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论