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)
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.
There's no difference between the two, it's the same.
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.
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.
[]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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With