xxxxxxxxxx
package main
import "fmt"
func main() {
// Creating a 2D slice of bytes
matrix := [][]byte{
{'a', 'b', 'c'},
{'d', 'e', 'f'},
{'g', 'h', 'i'},
}
// Accessing elements in the 2D slice
fmt.Println(matrix[0][0]) // Output: a
fmt.Println(matrix[1][1]) // Output: e
fmt.Println(matrix[2][2]) // Output: i
// Modifying an element in the 2D slice
matrix[1][1] = 'X'
// Printing the modified 2D slice
for _, row := range matrix {
for _, value := range row {
fmt.Printf("%c ", value)
}
fmt.Println()
}
// Output:
// a b c
// d X f
// g h i
}
xxxxxxxxxx
package main
import "fmt"
func main() {
// Creating a rectangular 2D slice of bytes
rows, cols := 3, 3
matrix := make([][]byte, rows)
for i := range matrix {
matrix[i] = make([]byte, cols)
}
// Initializing the 2D slice with values
value := byte('a')
for i := range matrix {
for j := range matrix[i] {
matrix[i][j] = value
value++
}
}
// Printing the 2D slice
for _, row := range matrix {
for _, val := range row {
fmt.Printf("%c ", val)
}
fmt.Println()
}
// Output:
// a b c
// d e f
// g h i
}