What is the difference between [] string and ... string in golang?

In the language of Go,

[]string is a string array

and we also use ...string as a parameter.

What is the difference?

Function Definition:

 func f(args ...string) {} 

Can I call this function as shown below?

 args := []string{"a", "b"} f(args) 
+72
string go
Oct 16
source share
4 answers

[]string is a string array

Technically, this is a fragment that references a base array

and we also use ...string as a parameter.

What is the difference?

As for the structure, nothing special. The data type obtained in both syntaxes is the same.

Parameter syntax ... creates a variable parameter. It will take zero or more string arguments and refer to them as a fragment.

As for calling f , you can pass a fragment of the string to a variable parameter with the following syntax:

 func f(args ...string) { fmt.Println(len(args)) } args := []string{"a", "b"} f(args...) 

This syntax is available either for a slice constructed using literal syntax, or for a slice representing a parameter with variable parameters (since there really are no differences between them).

http://play.golang.org/p/QWmzgIWpF8

+111
Oct. 16
source share

Both create an array of strings, but the difference is in what it's called.

 func f(args ...string) { } // Would be called like this: f("foo","bar","baz"); 

This allows you to accept a variable number of arguments (all of the same type)

A great example of this is fmt.Print and friends who can accept as little or less as you want.

+13
Oct. 16
source share

Here is what you want:

 var args []string = []string{"A", "B", "C"} func Sample(args ...string) { for _, arg := range args { fmt.Println(arg) } } func main() { Sample(args...) } 

Play: http://play.golang.org/p/N1ciDUKfG1

+4
Nov 19 '15 at 20:43
source share

It simplifies your function parameters. Here is an example ( https://play.golang.org/p/euMuy6IvaM ): The SampleEllipsis method takes from zero to many parameters of the same type, but args must be declared in the SampleArray method.

 package main import "fmt" func SampleEllipsis(args ...string) { fmt.Printf("Sample ellipsis : %+v\n",args) } func SampleArray(args []string) { fmt.Println("Sample array ") SampleEllipsis(args...) } func main() { // Method one SampleEllipsis([]string{"A", "B", "C"}...) // Method two SampleEllipsis("A", "B", "C") // Method three SampleEllipsis() // Simple array SampleArray([]string{"A", "B", "C"}) // Simple array SampleArray([]string{}) } 

Returns:

 Sample ellipsis : [ABC] Sample ellipsis : [ABC] Sample ellipsis : [] Sample array Sample ellipsis : [ABC] Sample array Sample ellipsis : [] 
+1
Nov 28 '16 at 12:36
source share



All Articles