Go/Arrays/Array Slice Insertion
From charlesreid1
The Go blog (this post: https://blog.golang.org/slices) gets lost on a (rather stupid and uninformative) topic, which is, array slices.
To insert an element into a slice of an array, we can do the following (NOTE: This is NOT the same as inserting an element into an array):
- Extend the slice window by 1
- Shift the upper part of the slice's underlying array data up by 1, using the copy function
- Copying FROM the variable slice, starting at index and running to the end
- Copying TO the variable slice, starting at index + 1 and running to the end
- Return the new slice
This operation WILL NOT affect the underlying data.
Here is the Insert function, plus a main method that calls it:
// Insert inserts the value into the slice at the specified index, // which must be in range. // The slice must have room for the new element. func Insert(slice []int, index, value int) []int { // Grow the slice by one element. slice = slice[0 : len(slice)+1] // Use copy to move the upper part of the slice out of the way and open a hole. copy(slice[index+1:], slice[index:]) // Store the new value. slice[index] = value // Return the result. return slice }
Aside from the stupidity of the example (not making clear why you would want to insert something into a slice of an array but not the array itself; not making clear the underlying data or the memory/reference model in Go).
Basically this whole blog post is a hot mess.
The confusion here is, the text seems to contradict the behavior of this function.
- The text describing this example insists we are passing a copy of the slice, but that copy should refer to the same data underneath.
- However, when we expand the length of the slice, and shift everything over, and insert a value, this doesn't affect the data underneath.
The answer: we aren't creating a slice by saying slice = orig[5:10]
, we are creating a slice by saying slice = make([]int, 4, 8)
and then copy(slice,orig)
.
When we call make, we're basically allocating an underlying array for a slice.
Related question on Stack Overflow
Go notes on Go
Go/Strings · Go/Arrays · Go/Slices
Go/Lists · Go/Maps · Go/Stacks · Go/Queues
Go/Naming Conventions · Go/Design Patterns
Go/Timing · Go/Profiling · Go/Benchmarking
Go/Tests · Go/Travis CI · Go/Makefiles
our vim + go setup uses custom solarized colors for Golang
|