douqiao2008 2016-01-20 21:22
浏览 42

如何在Golang中将接口参数传递给可变参数函数? [重复]

This question already has an answer here:

I have a variadic function Result func Results(messages ...Message) that accepts an interface Message. It works fine if I pass a single message of type Message, but if i pass a slice of message Result(slice...)

Here is the error I get:

prog.go:38: cannot use messages (type []*SampleMessage) as type []Message in argument to Results

Sample Code

</div>
  • 写回答

1条回答 默认 最新

  • dongshi6844 2016-01-20 21:28
    关注

    You need to restructure slightly. The issue is that a []*SampleMessage cannot convert to []Message. The way to handle this though, is to declare the messages slice as being of type []Message. Then you can append instances of SampleMessage to it without any problems and pass them into your variadic function with the ... syntax. Here's your example modified to compile; http://play.golang.org/p/cQUIZTz_vo - only change is on the first line of main where I have var messages []Message. If you try to do this in the reverse order (like use a []*SampleMessages then do a conversion with []Message(messages) as you pass it) it will fail. So as far as I know, this is the most practical way to solve your problem.

    评论

报告相同问题?

悬赏问题

  • ¥15 对于squad数据集的基于bert模型的微调
  • ¥15 为什么我运行这个网络会出现以下报错?CRNN神经网络
  • ¥20 steam下载游戏占用内存
  • ¥15 CST保存项目时失败
  • ¥15 树莓派5怎么用camera module 3啊
  • ¥20 java在应用程序里获取不到扬声器设备
  • ¥15 echarts动画效果的问题,请帮我添加一个动画。不要机器人回答。
  • ¥15 Attention is all you need 的代码运行
  • ¥15 一个服务器已经有一个系统了如果用usb再装一个系统,原来的系统会被覆盖掉吗
  • ¥15 使用esm_msa1_t12_100M_UR50S蛋白质语言模型进行零样本预测时,终端显示出了sequence handled的进度条,但是并不出结果就自动终止回到命令提示行了是怎么回事: