Unpacking slice/array into function arguments in Go: is there an analog of the spread operator from JS/Python?
Hello everyone. I've been writing Go recently, coming from Python and JavaScript. There it was very convenient to pass an array or list to a function that takes multiple arguments using the `*` operator (in Python) or `...` (spread in JS). For example, in Python I could do `my_func(*my_list)`.
Now in Go I have a function that takes multiple string arguments:
```go
func printNames(name1, name2, name3 string) {
fmt.Println(name1, name2, name3)
}
```
And I have a slice of strings:
```go
names := []string{"Alice", "Bob", "Charlie"}
```
How can I pass the elements of this slice to the `printNames` function as separate arguments? I tried just writing `printNames(names...)`, but the compiler complains that I cannot use a slice with `...` in a function with fixed parameters.
No answers yet.
Log in to leave an answer
Blogs