douquan1015 2019-06-03 20:42
浏览 84
已采纳

附加到实现的基本接口部分

Why the below doesn't work?

locations := make([]*LocationEvent, 0)
data := make([]Event, 0)
data = append(data, locations...)

where *LocationEvent (struct) implements Event (interface).

While the below works fine:

data = append(data, &LocationEvent{}, &LocationEvent{})

So how it is different when expanding the actual []*LocationEvent slice using ...?

  • 写回答

1条回答 默认 最新

  • dounangqie4819 2019-06-03 20:46
    关注

    The slice type must match the type of the variadic arguments in the append function exactly. locations is of type []*LocationEvent, and thus not compatible with []Event. There is no automatic "downcasting" in Go when working with slices.

    You have to copy the locations to a new slice of Event, or add the items of locations one-by-one to the data slice.

    For more explanation look here: https://stackoverflow.com/a/12754757/6655315

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

报告相同问题?

悬赏问题

  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料