Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

string

go

In the Go language,

[]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 like below?

args := []string{"a", "b"}  f(args) 
like image 325
user1746360 Avatar asked Oct 16 '12 04:10

user1746360


People also ask

What is difference between string [] and string?

String[] and String... are the same thing internally, i. e., an array of Strings. The difference is that when you use a varargs parameter ( String... ) you can call the method like: public void myMethod( String... foo ) { // do something // foo is an array (String[]) internally System.

Is string [] the same as array string?

There's no difference between the two, it's the same.

How many string types are there in Golang?

Go supports two styles of string literals, the double-quote style (or interpreted literals) and the back-quote style (or raw string literals). The zero values of string types are blank strings, which can be represented with "" or `` in literal.

What is type * string in Golang?

Sheza Naveed. string in Golang is a set of all strings that contain 8-bit bytes. By default, strings in Golang are UTF-8 encoded. Variable of type string is enclosed between double-quotes.


2 Answers

[]string is a string array

Technically 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

like image 87
I Hate Lazy Avatar answered Sep 26 '22 01:09

I Hate Lazy


Both create an array of strings, but the difference is in how it is 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, which can accept as few or as many arugments as you want.

like image 32
tylerl Avatar answered Sep 27 '22 01:09

tylerl