doushupu2521 2016-10-27 15:15
浏览 26
已采纳

将结构复制到实现接口的结构中

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条回答 默认 最新

  • dongwen7423 2016-10-27 15:19
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 RL+GNN解决人员排班问题时梯度消失
  • ¥15 统计大规模图中的完全子图问题
  • ¥15 使用LM2596制作降压电路,一个能运行,一个不能
  • ¥60 要数控稳压电源测试数据
  • ¥15 能帮我写下这个编程吗
  • ¥15 ikuai客户端l2tp协议链接报终止15信号和无法将p.p.p6转换为我的l2tp线路
  • ¥15 phython读取excel表格报错 ^7个 SyntaxError: invalid syntax 语句报错
  • ¥20 @microsoft/fetch-event-source 流式响应问题
  • ¥15 ogg dd trandata 报错
  • ¥15 高缺失率数据如何选择填充方式