gotchagoCritical
What is the difference between []string and ...string in golang?
Viewed 0 times
andbetweenthedifferencegolangstringwhat
Problem
In the Go language,
and we also use
What is the difference?
Function definition:
Can I call this function like below?
[]string is a string arrayand we also use
...string as a parameter.What is the difference?
Function definition:
func f(args ...string) {}Can I call this function like below?
args := []string{"a", "b"}
f(args)Solution
[]string is a string arrayTechnically it's a slice that references an underlying array
and we also use
...string as a parameter.What is the difference?
With respect to the structure, nothing really. The data type resulting from both syntax is the same.
The
... parameter syntax makes a variadic parameter. It will accept zero or more string arguments, and reference them as a slice.With respect to calling
f, you can pass a slice of strings into the variadic parameter with the following syntax:func f(args ...string) {
fmt.Println(len(args))
}
args := []string{"a", "b"}
f(args...)This syntax is available for either the slice built using the literal syntax, or the slice representing the variadic parameter (since there's really no difference between them).
http://play.golang.org/p/QWmzgIWpF8
Code Snippets
func f(args ...string) {
fmt.Println(len(args))
}
args := []string{"a", "b"}
f(args...)Context
Stack Overflow Q#12907653, score: 144
Revisions (0)
No revisions yet.