Joseph Swaminathan
Joseph Swaminathan

Reputation: 115

Golang : Variable argument

When I compile the following program

func myPrint(v ...interface{}) {
        fmt.Println("Hello", v...)
}
func main() {
    myPrint("new", "world")
}

I get a compilation error

too many arguments in call to fmt.Println

I thought v... is going to expand into 2nd, 3rd arguments and the fmt.Println would see three item variadic argument list. I thought it would be equivalent to

fmt.Println("Hello", "new", "world")

Why is it giving an error.

Upvotes: 4

Views: 4506

Answers (2)

Gordon Childs
Gordon Childs

Reputation: 36169

Try this. It prepends Hello to the variadic arguments, then prints them all at once with println.

package main

import "fmt"

func myPrint(v ...interface{}) {
    a := append([]interface{}{"Hello"}, v...)   // prepend "Hello" to variadics
    fmt.Println(a...)                           // println the whole lot
}
func main() {
    myPrint("new", "world")
}

Upvotes: 6

SnoProblem
SnoProblem

Reputation: 1939

You're mis-using the variadic shorthand in your call to fmt.Println(). What you're actually sending is 2 arguments: a single string, then the slice of type interface{} expanded. The function call will not concatenate that into a single slice.

This design will compile and run with the results you're expecting:

func myPrint(v ...interface{}) {
    fmt.Print("Hello ")
    fmt.Println(v...)
}

func main() {
    myPrint("new", "world")
}

Upvotes: 2

Related Questions