英文:
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
答案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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论