0

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

Anthony
  • 41
  • 1
  • 5
  • 2
    `[]*SampleMessage != []Message`; you need to change `messages`'s declaration to: `var messages []Message` –  Jan 20 '16 at 21:25
  • It works fine if I pass Results(messages[0], messages[1]), so why won't Results([ ]SampleMessage). I guess you might be right though – Anthony Jan 20 '16 at 21:31

1 Answers1

3

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.

evanmcdonnal
  • 46,131
  • 16
  • 104
  • 115