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

huangapple go评论83阅读模式
英文:

How to pass an interface argument to a variadic function in Golang?

问题

我有一个可变参数函数func Results(messages ...Message),它接受一个接口Message。如果我传递一个类型为Message的单个消息,它可以正常工作,但如果我传递一个消息切片Result(slice...),我会得到以下错误:

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

示例代码

英文:

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

答案1

得分: 3

你需要稍微重构一下。问题在于[]*SampleMessage无法转换为[]Message。处理这个问题的方法是将messages切片声明为[]Message类型。然后,你可以将SampleMessage的实例追加到其中,而不会出现任何问题,并使用...语法将它们传递到可变参数函数中。这是修改后可以编译的示例:http://play.golang.org/p/cQUIZTz_vo - 唯一的变化是在main函数的第一行,我将var messages []Message。如果你尝试以相反的顺序进行操作(例如使用[]*SampleMessages然后使用[]Message(messages)进行转换),它将失败。据我所知,这是解决你的问题的最实用的方法。

英文:

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.

huangapple
  • 本文由 发表于 2016年1月21日 05:22:14
  • 转载请务必保留本文链接:https://go.coder-hub.com/34910808.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定