In Golang, you can access elements by index in a slice using square brackets []
. Here is an example:
package main
import "fmt"
func main() {
// Create a slice
slice := []int{1, 2, 3, 4, 5}
// Access an element at index 2
fmt.Println(slice[2]) // Output: 3
// Access multiple elements using a slice index range
fmt.Println(slice[1:4]) // Output: [2 3 4]
}
In the above example, slice[2]
accesses the element at index 2, which is 3
. The syntax slice[1:4]
accesses multiple elements from index 1 to index 3 (exclusive), which are [2 3 4]
. Note that the index in Golang starts from 0.