Why are lists used infrequently in Go?

I’m new to Go, and quite excited about it. But, in all the languages I’ve worked with extensively: Delphi, C#, C++, Python - Lists are very important because they can be dynamically resized, as opposed to arrays.

In Golang, there is indeed a list.List struct, but I see very little documentation about it - whether in Go By Example or the three Go books that I have - Summerfield, Chisnal and Balbaert - they all spend a lot of time on arrays and slices and then skip to maps. In souce code examples I also find little or no use of list.List .

It also appears that, unlike Python, Range is not supported for List - big drawback IMO. Am I missing something?

Slices are certainly nice, but they still need to be based on an array with a hard coded size. That’s where List comes in. Is there a way to create an array /slice in Go without a hard coded array size? Why is List ignored?

1 Like

Just about always when you are thinking of a list - use a slice instead in Go. Slices are dynamically re-sized. Underlying them is a contiguous slice of memory which can change size.

They are very flexible as you’ll see if you read the SliceTricks wiki page.

Here is an excerpt :-

Copy

b = make([]T, len(a))
copy(b, a) // or b = append([]T(nil), a...)

Cut

a = append(a[:i], a[j:]...)

Delete

a = append(a[:i], a[i+1:]...) // or a = a[:i+copy(a[i:], a[i+1:])]

Delete without preserving order

a[i], a = a[len(a)-1], a[:len(a)-1]

Pop

x, a = a[len(a)-1], a[:len(a)-1]

Push

a = append(a, x)

Update : Here is a link to a blog post all about slices from the go team itself, which does a good job of explaining the relationship between slices and arrays and slice internals.

Refer: stackoverflow