mardi 7 juin 2022

Why Go's append NEED create and return a new slice? [duplicate]

In Go, when we use append, we use it like this:

a := make([]int, 0)
a = append(a, 1)

In this sample, append will create a new slice (we know that go will always do this when trigger slice's grow algorithm), which has different memory location from the old one, but WHY?

Consider we wants a iterator pattern, code like this:

type SliceIterator struct {
    index int
    slice []int
}

func (i *SliceIterator) HasNext() bool {
    return i.index < len(i.slice)
}

func (i *SliceIterator) Next() int {
    i.index += 1
    return i.slice[i.index-1]
}

If we pass a slice into an iterator and we append some elements to the slice outside, the slice inside the iterator may not be what we want and the iterator may be useless.

So is there any way to reslove this problem?

And the most important, why Go designs its append like this? I think it can just reallocate the pointer to the actual array but no need to create a new slice, just change the pointer, len and capacity inside the original slice.

Aucun commentaire:

Enregistrer un commentaire