Why are lists used infrequently in Go?

前端 未结 7 1290
眼角桃花
眼角桃花 2021-01-30 07:57

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 dynam

7条回答
  •  礼貌的吻别
    2021-01-30 08:39

    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.

提交回复
热议问题