Home > Backend Development > Golang > Why Can't I Mix 'Exploded' Slices and Regular Parameters in Go's Variadic Functions?

Why Can't I Mix 'Exploded' Slices and Regular Parameters in Go's Variadic Functions?

Susan Sarandon
Release: 2024-12-17 19:13:19
Original
513 people have browsed it

Why Can't I Mix

Mixing "Exploded" Slices and Regular Parameters in Variadic Functions

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)
}
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template