Senior
Can you demonstrate how to access the fourth element of a slice?
sobes.tech AI
Answer from AI
In Go, access to slice elements is done through an index in square brackets, starting from 0.
To get the fourth element of a slice, you need to access index 3:
package main
import "fmt"
func main() {
s := []int{10, 20, 30, 40, 50}
fourth := s[3] // index 3 is the fourth element
fmt.Println(fourth) // Will print: 40
}
It is important to ensure that the length of the slice is at least 4, otherwise an "index out of range" panic will occur.