How to iterate multidimensional slice using for range in Golang 1.20
In this video we are going to generate source code for the GoLang Program, How to iterate multidimensional slice using for range using chatGPT.
After generating we will verify and run the generated code.
IMPORTANT NOTE on SOURCE CODE: only source code that are acceptable by the youtube description box will be displayed.
In this program I have replaced the angled brackets with > or <. once you copy the source code to editor replace it with greater than or less than symbols respectively.
##############SOURCE CODE#########################
package main
import "fmt"
func main() {
// Declare a multidimensional slice of integers
slice := [][]int{{1, 2}, {3, 4, 5}, {6, 7, 8, 9}}
// Iterate over the slice using the range keyword
for row, rowSlice := range slice {
for col, value := range rowSlice {
// Print the element at the current row and column
fmt.Printf("slice[%d][%d] = %d\n", row, col, value)
}
}
}
##############END OF SOURCE CODE#########################
Below is the explanation for the program:
In this program, we declare a multidimensional slice of integers using the syntax slice := [][]int{{1, 2}, {3, 4, 5}, {6, 7, 8, 9}}.
This creates a slice with three rows, where each row is a slice of integers of varying lengths.
We then use the range keyword to iterate over the multidimensional slice.
The first range statement iterates over the rows of the slice and assigns the current row index to the variable row and the current row slice to the variable rowSlice.
The second range statement iterates over the elements in the current row slice and assigns the current column index to the variable col and the current value to the variable value.
Inside the nested loops, we use the fmt.Printf() function to print the current row and column indices, as well as the element at that position in the slice.
Using range to iterate over a multidimensional slice is often simpler and more concise than using nested for loops, especially for irregularly shaped slices.
#go #goprogramming #golang #golangtutorial #golanguage