I was reading through Go's compress/flate
package, and I found this odd piece of code [1]:
n := int32(len(list))
list = list[0 : n+1]
list[n] = maxNode()
In context, list
is guaranteed to be pointing to an array with more data after. This is a private function, so it can't be misused outside the library.
To me, this seems like a scary hack that should be a runtime exception. For example, the following D code generates a RangeError:
auto x = [1, 2, 3];
auto y = x[0 .. 2];
y = y[0 .. 3];
Abusing slices could be done more simply (and also look more safe) with the following:
x := []int{1, 2, 3}
y = x[:2]
y = append(y, 4) // x is now [1, 2, 4] because of how append works
But both solutions seem very hacky and scary and, IMHO, should not work as they do. Is this sort of thing considered idiomatic Go code? If so, which of the the above is more idiomatic?
[1] - http://golang.org/src/pkg/compress/flate/huffman_code.go#L136