How to get the last element of a slice in Go? Is there a built-in function?
Hello! I just started learning Go after Python, and I have a problem with slices. In Python, I'm used to getting the last element of a list via `my_list[-1]`, but this syntax doesn't work in Go — the compiler gives an error "invalid slice index -1".
I tried writing something like `arr[len(arr) - 1]`, but it looks cumbersome and, honestly, I'm not sure if it's correct. For example, what if the slice is empty? I had this code:
```go
package main
import "fmt"
func main() {
fruits := []string{"apple", "banana", "cherry"}
// How to get "cherry"?
fmt.Println(fruits[-1]) // Error!
fmt.Println(fruits[len(fruits)-1]) // Works?
}
```
But I'm afraid that if the slice turns out to be empty, then `len(fruits) - 1` will give -1, and the program will crash with a panic.
No answers yet.
Log in to leave an answer