laurent
laurent

Reputation: 90804

How to pass variadic parameters from one function to another in Go

I'm trying to pass variadic parameters from one function to another in Go. Basically something like this:

func CustomPrint(a ...interface{}) (int, error) {
    // ...
    // Do something else
    // ...

    return fmt.Print(a)
}

However when I do this a is printed like a slice, not like a list of arguments. i.e.

fmt.Print("a", "b", "c") // Prints "a b c"
CustomPrint("a", "b", "c") // Print "[a b c]"

Any idea how to implement this?

Upvotes: 4

Views: 858

Answers (1)

Volker
Volker

Reputation: 42431

Use ... when calling with a slice:

package main
import "fmt"
func CustomPrint(a ...interface{}) (int, error) {
     return fmt.Print(a...)
}
func main() {
     CustomPrint("Hello", 1, 3.14, true)
}

Upvotes: 7

Related Questions