Reslicing
Explore how to reslice slices in Go by changing their length dynamically within the capacity of their underlying arrays. Learn through examples how to extend slices, initialize elements, and manage collections efficiently. This lesson helps you handle slice operations such as uploading, deleting, and listing items in applications, using practical code techniques.
We'll cover the following...
Introduction
We saw that a slice is often made smaller than the underlying array initially, like this:
slice1 := make([]type, start_length, capacity)
Here, start_length is the length of slice and capacity is the length of the underlying array. This is useful because now our slice can grow until capacity. Changing the length of the slice is called reslicing, it is done like:
slice1 = slice1[0:end]
where end is another end-index (length) than before.
Resizing a slice by 1 can be done as follows:
sl = sl[0:len(sl)+1] // extend length by 1
A slice can be resized until it occupies the whole underlying array.
Explanation
The following program is a detailed implementation ...