Slices

suggest change

A slice is a growable sequence of values of the same type.

Other languages call them arrays or vectors.

The memory used by a slice is a fixed-size array. A slice is a view into that array.

Slice has length and capacity.

Capacity is the number of elements from the slice's first element to the end of its underlying array.

Length is the current number of elements in the slice.

The difference between capacity and length is how many elements can be appended before append must allocate a new underlying array.

Zero value of a slice is nil.

Basics of slices

	slice := make([]int, 0, 5)
	// append element to end of slice
	slice = append(slice, 5)
	// append multiple elements to end
	slice = append(slice, 3, 4)
	fmt.Printf("length of slice is: %d\n", len(slice))
	fmt.Printf("capacity of slice is: %d\n", cap(slice))
length of slice is: 3
capacity of slice is: 5

Create a slice

Length and capacity

Append to slice

Filter a slice

Remove elements from slice

Duplicate a slice

Zero value of slice

Slice tricks

Optimize by pre-allocating slice

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents