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.

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

报告相同问题?

悬赏问题

  • ¥15 centos7.9 IPv6端口telnet和端口监控问题
  • ¥120 计算机网络的新校区组网设计
  • ¥20 完全没有学习过GAN,看了CSDN的一篇文章,里面有代码但是完全不知道如何操作
  • ¥15 使用ue5插件narrative时如何切换关卡也保存叙事任务记录
  • ¥20 海浪数据 南海地区海况数据,波浪数据
  • ¥20 软件测试决策法疑问求解答
  • ¥15 win11 23H2删除推荐的项目,支持注册表等
  • ¥15 matlab 用yalmip搭建模型,cplex求解,线性化处理的方法
  • ¥15 qt6.6.3 基于百度云的语音识别 不会改
  • ¥15 关于#目标检测#的问题:大概就是类似后台自动检测某下架商品的库存,在他监测到该商品上架并且可以购买的瞬间点击立即购买下单