go nested slice
Sure! Here is an example of working with nested slices in Go:
package main
import "fmt"
func main() {
// Create a nested slice
nestedSlice := [][]int{{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}
// Accessing elements in the nested slice
fmt.Println(nestedSlice[0][0]) // Output: 1
fmt.Println(nestedSlice[1][2]) // Output: 6
// Modifying elements in the nested slice
nestedSlice[2][1] = 10
fmt.Println(nestedSlice) // Output: [[1 2 3] [4 5 6] [7 10 9]]
}
Explanation:
1. First, we create a nested slice using the shorthand syntax [][]int{{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}
. This creates a slice of slices, where each inner slice contains integers. In this example, we have a 3x3 matrix represented as a nested slice.
To access elements in the nested slice, we use the indexing syntax
nestedSlice[i][j]
, wherei
represents the row index andj
represents the column index. For example,nestedSlice[0][0]
returns the element at the first row and first column, which is1
. Similarly,nestedSlice[1][2]
returns the element at the second row and third column, which is6
.We can also modify elements in the nested slice using the same indexing syntax. In the example,
nestedSlice[2][1] = 10
modifies the element at the third row and second column, changing it from8
to10
. The resulting nested slice is[[1 2 3] [4 5 6] [7 10 9]]
.
This example demonstrates how to create, access, and modify elements in a nested slice in Go. Nested slices are useful for representing multi-dimensional data structures, such as matrices or grids.