Go: Last item in slice
To read the last element:
a := []string{"A", "B", "C"}
s := a[len(a)-1] // C
To remove it:
a = a[:len(a)-1] // [A B]
(Go doesn't have negative indexing like Python does.)
Watch out for memory leaks
If the slice is permanent and the element temporary, you may want to remove the reference before removing the element from the slice:
a[len(a)-1] = "" // write zero value to avoid memory leak
a = a[:len(a)-1] // [A B]
Comments
Be the first to comment!