Using ellipses in a variadic function call

62 views
Skip to first unread message

Deiter

unread,
Feb 27, 2021, 10:03:19 PM2/27/21
to golang-nuts
Go: go1.15.8 darwin/amd64
OS: MacOS 11.2.1

The program here includes a function with variadic arguments:
    func outputStrings(strings …string)

Individual strings can be passed specifically:
    outputStrings("foo", "bar")

You can also use an ellipses to covert the content of an array to the individual arguments:

   myStrings := []string{"foo", "bar"}
    outputStrings(myStrings...)

I expected that this would work as well:
    outputStrings("foo", "bar", myStrings...)

But it leads to:

    # variadic
    ./variadic.go:17:15: too many arguments in call to outputStrings
    have (string, string, []string...)
    want (...string)

The error message is clear, and easily worked around, so my question isn’t so much why the error occurred, by rather should it have occurred? It seems to me that the format of the function call make it clear and unambiguous to the compiler what’s being passed.

There was similar discussion here, but it was left unresolved.

Ian Lance Taylor

unread,
Feb 27, 2021, 10:20:34 PM2/27/21
to Deiter, golang-nuts
Reply all
Reply to author
Forward
0 new messages