DEV Community

Manu
Manu

Posted on

Dynamic parameters in Go

#go

Coming from a dynamic programming background it was a bit of getting used to, to the typed ecosystem of go especially with function signatures.

One of the things that was boggling me was how to pass dynamic parameters to a function.
In ruby we could

def someFunc(arg1, *moreArgs)
  puts moreArgs
end

Now we could call somefunc("hello", "george", "joseph")

It was all simple there, but coming to go, it wasn't that straightforward, although go provides a way to do this. Look at the below snippet

func someFunc(arg1 string, a ...string) {
    fmt.Println(arg1)
    fmt.Println(arg1, a)
    fmt.Println()
}   

Observing the snippet line by line, notice the last parameter of someFunc, it is called variadic parameter. From the go docs

 If f is variadic with a final parameter p of type ...T, then within f the type of p is equivalent to type []T. If f is invoked with no actual arguments for p, the value passed to p is nil. Otherwise, the value passed is a new slice of type []T with a new underlying array whose successive elements are the actual arguments, which all must be assignable to T. The length and capacity of the slice is therefore the number of arguments bound to p and may differ for each call site.

Okay, what it means is that if the final parameter of a method is of type ...T, then it is considered as type []T inside that method. What this means is that it works similar to *moreArgs in ruby. If we need to pass multiple arguments of type T, we can and they all will be available in the slice []T.

We could call the function as below:

    someFunc("hello")
    someFunc("hello", "apple")
    someFunc("hello", "apple", "orange")

Top comments (0)