1

Given a function declared as

func foo(bars ...string) {
    // ...
}

I'd like to call this like so:

bar1 := "whiskey bar"
rest := []string{"vodka bar", "wine bar"}
foo(bar1, rest...)

but this doesn't compile; the last line errors with this message:

have (string, []string...)
want (...[]string)

Is there a way I can declare a variadic function so that it can be called with both zero or more parameters that are values, and zero or one array of values (at the end)?

Tomas Aschan
  • 58,548
  • 56
  • 243
  • 402
  • 1
    Unfortunately there isn't a way that would satisfy both of your conditions, the best you can do, i think, is something like this: `foo(append([]string{bar1}, rest...)...)`. – mkopriva May 02 '17 at 11:26
  • 1
    Also have a look at this [so answer](http://stackoverflow.com/a/28626170/965900). – mkopriva May 02 '17 at 11:31
  • Also related: [Is it possible to trigger compile time error with custom library in golang?](http://stackoverflow.com/questions/37270743/is-it-possible-to-trigger-compile-time-error-with-custom-library-in-golang/37271129#37271129) – icza May 02 '17 at 11:40

1 Answers1

1

You'd have to change the signature to func foo(some string, bars ...string) as explained in the docs. More in the playground: https://play.golang.org/p/xlsCKzhj5y

Michael Hausenblas
  • 13,162
  • 4
  • 52
  • 66