Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 724
laurent Avatar asked Sep 03 '25 05:09

laurent


1 Answers

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)
}
like image 142
Volker Avatar answered Sep 05 '25 01:09

Volker