douqian5920 2016-05-03 18:33
浏览 68
已采纳

如何将“子”结构传递给接受“父”结构的函数?

I'm trying to use inheritance in Go, and although inheritance isn't 'technically' supported (as far as I know), you can get similar functionality by using anonymous fields.

Here's how I'm defining 'inheritance' for across two structs:

//Parent struct:

type FSEntity struct {
    guid GUIDNumber
}

//Child struct:

type DataBlock struct {
    FSEntity
    data []byte
}

I now have a function defined as following, which is supposed to accept an instance of the parent struct FSEntity:

Put(entity FSEntity) {....}

But when I try passing an instance of DataBlock (which through inheritance is also FSEntity) into the Put function above like so:

guidNumber := GUIDNumber(1234)
value := []byte("sample string")
dataBLock := DataBlock{FSEntity{guidNumber}, value}

Put(dataBLock)

On the last line above, I get this error:

cannot use dataBLock (type DataBlock) as type FSEntity in argument to Put

How do I resolve this ?

  • 写回答

4条回答 默认 最新

  • dongxiong2000 2016-05-03 18:44
    关注

    I think the terminology you're using is causing you problems. In the put, you simply need to reference the inner struct like so; Put(dataBLock.FSEntity)

    But to clarify, there is no parent/child relationship here. You're using a language feature called embedding and works like composition (ie one type is composed of others) only the things you embed have their fields/methods hoisted to the embedding scope. For that reason you can't pass in the type you're calling the 'child' because there is no polymorphic behavior here like when you inherit from a type, instead you're type is composed of that but you can access it's fields without the extra level of indirection. Since your method accepts the embedded type as an argument, you have to explicitly reference it to pass only that. The outer struct is in no way that type.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度