8

Last item in a slice/array

 3 years ago
source link: https://yourbasic.org/golang/last-item-in-slice/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

Last item in a slice/array

yourbasic.org/golang
surgical-removal.jpg

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

orange-thumb.jpg

Slices and arrays in 6 easy steps

Share:             


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK