Avatar ·

How to get the last element of a slice in Go?

Hi everyone! I just started learning Go and ran into a problem. I have a slice of strings `names := []string{"Alice", "Bob", "Charlie"}`. I need to get the last element of this slice to display it on the screen or process it. In Python I would write `names[-1]` and it would work. But in Go, this notation causes a compilation error: `invalid slice index -1`. I googled it and found that Go doesn't support negative indices. So far I've only come up with this workaround: ```go package main import "fmt" func main() { names := []string{"Alice", "Bob", "Charlie"} last := names[len(names)-1] fmt.Println(last) } ``` This works, but it doesn't seem very reliable to me, especially if the slice turns out to be empty. Yesterday I had a bug: I forgot to check that the