Why are lists used infrequently in Go?

前端 未结 7 1357
眼角桃花
眼角桃花 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:47

    Note that Go slices can be expanded via the append() builtin function. While this will sometimes require making a copy of the backing array, it won't happen every time, since Go will over-size the new array giving it a larger capacity than the reported length. This means that a subsequent append operation can be completed without another data copy.

    While you do end up with more data copies than with equivalent code implemented with linked lists, you remove the need to allocate elements in the list individually and the need to update the Next pointers. For many uses the array based implementation provides better or good enough performance, so that is what is emphasised in the language. Interestingly, Python's standard list type is also array backed and has similar performance characteristics when appending values.

    That said, there are cases where linked lists are a better choice (e.g. when you need to insert or remove elements from the start/middle of a long list), and that is why a standard library implementation is provided. I guess they didn't add any special language features to work with them because these cases are less common than those where slices are used.

提交回复
热议问题