Suppose I have a sparsely populated slice and want to read/write to an element by index that may or may not be outside the capacity of the slice.
What is the idiomatic way of writing to s[x] when x may exceed the capacity?
Suppose I have a sparsely populated slice and want to read/write to an element by index that may or may not be outside the capacity of the slice.
What is the idiomatic way of writing to s[x] when x may exceed the capacity?
You'd need to check if x
is outside the slice's range and extend the slice if it is (append zeros or something like that). There are no magic shortcuts. To "extend" a slice you can do:
a = append(a, make([]T, j)...)
Where a
is the slice, T
is the type of its contents and j
is by how much you want to extend it.