Last item in a slice/array

yourbasic.org/golang

Read last element

Use the index len(a)-1 to access the last element of a slice or array a.

a := []string{"A", "B", "C"}
s := a[len(a)-1] // C
Go doesn't have negative indexing like Python does. This is a deliberate design decision — keeping the language simple can help save you from subtle bugs.

Remove last element

a = a[:len(a)-1] // [A B]

Watch out for memory leaks

Warning: If the slice is permanent and the element temporary, you may want to remove the reference to the element before slicing it off.
a[len(a)-1] = "" // Erase element (write zero value)
a = a[:len(a)-1] // [A B]

Further reading

Slices and arrays in 6 easy steps

Share this page: