This is a question not a bug.
I have a slice of pointers to dataset
objects, thus:
var Datasets []*Dataset
(actually this is a field in a struct, but the issue is the same)
I have a variable called timeStamp
which is used as an index into this array, for example:
name:= *Datasets[timestamp].Name
Each new Dataset
is added to the Datasets
slice as follows:
Datasets = append(user.Datasets, &new_dataset)
My question is: what is the index of the new item just added to Datasets
? I assume append
simply adds the new item at the “end” of the slice (see below for a slightly more precise definition of “end”). But in the documentation that I’ve seen (for example here), it doesn’t actually say what is the array index of the appended element goes. So in this example we have:
func main() {
var s []int
printSlice(s)
// append works on nil slices.
s = append(s, 0)
printSlice(s)
// The slice grows as needed.
s = append(s, 1)
printSlice(s)
// We can add more than one element at a time.
s = append(s, 2, 3, 4)
printSlice(s)
}
but this does not explictly say what I will find in, say, s[0]
or s[1]
.
Intuitively it’s kind of obvious that s[0]=0
, s[1]=1
, and so on. But I don’t want to rely on a behaviour that isn’t documented, or explicitly stated.
Maybe the difficulty is clearer if we consider the effect of deleting an element in the middle of the slice. Will all the slice elements be moved down and if so, will a new element be appended at the new “end” of the result? Or will there simply be an unpopulated element in the slice, and the effect of ‘append’ could then be to make use of the vacated space? And is the choice left to the implementor, or is it laid down in the Go specifications?
Another way of stating this question, a bit more generally, is perhaps to ask whether the order of the elements in the slice, after a sequence of appends, preserves the actual order in which new elements were added in this sequence.
Probably the question is answered in more detailed documentation on actions like delete, but I haven’t yet found it.
Not an urgent question but I’d welcome an answer because, as mentioned above, I don’t want to rely on a behaviour that isn’t guaranteed.
A