Go does not allow mixing "exploded" slices with regular parameters in variadic functions. This is evident in the following example:
func main() { stuff := []string{"baz", "bla"} foo("bar", stuff...) // Error: too many arguments in call to foo } func foo(s ...string) { fmt.Println(s) }
According to the Go Language Specification, a variable length argument can be specified in two ways: enumerating the elements or using an existing slice. Mixing the two is not permitted.
When elements are enumerated, a new slice is created where the elements become the values of the variadic parameter. However, when an existing slice is used with ..., no new slice is created and the original slice becomes the variadic parameter.
Passing both a single element and a slice will result in a type mismatch, leading to a compiler error. Mixing the two options would require allocating a new slice, but Go does not support this behavior.
The error message "too many arguments in call to foo" indicates that the compiler expects a single slice or a list of elements, but not a combination of both. To resolve this issue, either remove stuff... or enumerate the elements individually.
The above is the detailed content of Why Can't I Mix 'Exploded' Slices and Regular Parameters in Go's Variadic Functions?. For more information, please follow other related articles on the PHP Chinese website!