views:

116

answers:

2

I'm currently playing with Google Go.
There's a lot of ways to declare and/or initialize variables.
Can someone explains pros/cons of each way (samples, as far as i know, below) :

    var strArr0 *[10]string = new([10]string)

    var strArr1 = new([10]string)

    var strArr2 = make([]string,10)

    var strArr3 [10]string

    strArr4 := make([]string,10)

What is your preferred syntax, and why ?
Thanks, SO folks !

+1  A: 

First of all you should understand the distinction between arrays and slices. Arrays are treated as values, so if you pass them to functions they will get copied. Slices, on the other hand, are references to the underlying array, so if you pass a slice to a function, the function variable will still refer to the same underlying array.

In your examples, the first two are identical, it's just the first specifies the type in the variable declaration. Go let's you do that, and it may help in some cases -- like when you're trying to declare a variable to be an interface instead of a value (i.e var i io.Reader = os.Open(...)).

The third and the fifth (var strArr2 = make([]string,10), strArr4 := make([]string,10) are equivalent, but the latter uses the short-hand form of variable declaration, which can often save a lot of typing.

The fourth just declares an array value.

I rarely deal with arrays in my code unless I'm working with network data. So my preferred syntax is:

s := make([]string, 10)
marketer
jlv
I've never had to use fixed-size string arrays( 1 or 2 ), but I use slices of string arrays (3 and 5) all the time because that's what a vector.StringVector is. I've worked with fixed-size arrays when parsing network data. For instance, the [zlib reader](http://golang.org/src/pkg/compress/zlib/reader.go) reads some encoding options into the fixed-size array `scratch [4]byte`.
marketer
Btw, even if 4) seems to declare an array value without initializing it, i.e. without the use of 'new' or 'make', it's (surprisingly ?) still possible to fill the related array : var strArr3 [10]stringstrArr3[0] = "bla"os.Stdout.WriteString(strArr3[0]+"\n")displays "bla".
jideel