0

I have just started to pick up go, and I was going over the data structures. I am used to having a dynamic array like list in python or std::vector in C++, but I don't see anything similar in go. The nice things about dynamic array is that it has O(1) time complexity to add a new element, and O(1) time complexity for indexing.

First I thought that slice is it, but then I realized that when I used append function, the whole slice is being copied, and then therefore it is an O(N) operations as opposed to O(1) in dynamic array.

Then I came across list but this is a doubly linked list, which means that indexing is O(N), as opposed to O(1).

Am I missing the data structure I am looking for?

ruakh
  • 175,680
  • 26
  • 273
  • 307
Akavall
  • 82,592
  • 51
  • 207
  • 251
  • 3
    Voting to reopen. The answers to the linked question say *that* the OP should use slices, but they don't actually explain the aspect of slices that the OP was concerned about. (All of the answers to that question, even the highly-upvoted ones, would merit massive downvotes if posted here.) – ruakh Dec 15 '14 at 16:52

1 Answers1

10

First I thought that slice is it, but the[n] I realized that when I used append function, the whole slice is being copied, and then therefore it is an O(N) operations as opposed to O(1) in dynamic array.

This is not correct.

Per The Go Programming Language Specification, append examines the capacity of the array that backs the slice, and only allocates new memory (copying the slice) if there's not enough room in the backing array. [link] I don't see anything in the specification proper that specifies how much memory it should allocate, but according to the blog post you link to, the new block of memory will be 1.5 times the current size of the slice. That means that, after a reallocating/copying insertion, the next n/2 insertions will not require reallocating/copying. The overall effect is amortized O(1) time. This is the same approach used by the examples you mention in other languages (list in Python, std::vector in C++).

So, slices are exactly what you need.

ruakh
  • 175,680
  • 26
  • 273
  • 307