Best way to initite array of strings

I know an empty array canbe initiated with one of the below, if there are others pls advice:

lines := []string{} 
// Or
lines := make([]string, 0)
// Or
var lines []string

What are the differences betwwen these methods, are they all equivalent, any special use for any of them?

CodeReviewComments

Declaring Empty Slices

When declaring an empty slice, prefer

var t []string

over

t := []string{}

The former declares a nil slice value, while the latter is non-nil but zero-length. They are functionally equivalent—their len and cap are both zero—but the nil slice is the preferred style.

Note that there are limited circumstances where a non-nil but zero-length slice is preferred, such as when encoding JSON objects (a nil slice encodes to null , while []string{} encodes to the JSON array [] ).

. . .

one

This defines an empty slice lines

two

The result of this should be the same as the above. Use the above unless you want to set the size or capacity to non-zero, eg

lines := make([]string, 5) // len(lines) == 5
lines := make([]string, 0, 5) // len(lines) == 0, cap(lines) = 5

The latter of these is useful for when appending to a slice.

three

This makes a nil slice which isn’t quite the same thing as an empty slice. A nil slice is perfectly well behaved, has len(lines) == 0 and cap(lines) == 0. I would use this form if I was planning to append some (or no) items to it.

Interestingly when I compiled a simple function with each init method in, one and three produced identical code - basically zeroing the slice structure. two produced a lot more code, actually allocating stuff on the heap.

1 Like

Appreciate your detailed answer :kissing_heart:

1 Like

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.