Go - Multidimensional Slices Example

1. Introduction

Multidimensional slices in Go are not provided as a built-in data structure but can be emulated using slices of slices. These data structures are useful for representing complex data models, like matrices. In this blog post, we’ll create and work with a two-dimensional slice in Go.

Definition

A multidimensional slice in Go is a slice where each element is also a slice. By creating slices of slices, you can construct structures similar to two-dimensional arrays commonly used in other programming languages.

2. Program Steps

1. Define and initialize a two-dimensional slice.

2. Assign values to individual elements.

3. Iterate over the elements using nested loops.

4. Print out the two-dimensional slice.

3. Code Program

package main

import "fmt"

func main() {
	// Step 1: Define a two-dimensional slice
	var matrix [][]int

	// Initialize a two-dimensional slice with 3 rows
	for i := 0; i < 3; i++ {
		row := make([]int, 3) // Create a slice with 3 columns
		matrix = append(matrix, row)
	}

	// Step 2: Assign values to individual elements
	matrix[0][0] = 1
	matrix[1][1] = 2
	matrix[2][2] = 3

	// Step 3: Iterate over the elements with nested loops
	fmt.Println("2D Slice:")
	for _, row := range matrix {
		for _, col := range row {
			fmt.Printf("%d ", col)
		}
		fmt.Println()
	}
}

Output:

2D Slice:
1 0 0
0 2 0
0 0 3

Explanation:

1. package main - The package declaration for the Go program.

2. import "fmt" - Imports the Format package, which is used for input and output.

3. matrix is declared as a slice of slices of integers.

4. A for loop runs three times to initialize the matrix with three rows, each being a slice with three columns (initialized to zero value for int).

5. Individual elements of the matrix are assigned values such as matrix[0][0] = 1.

6. Another nested for loop using range iterates over each row and column of the matrix, printing each element followed by a space. After each row, a newline is printed to format the output like a matrix.

7. The output shows a formatted two-dimensional slice with three rows and three columns, with values assigned to the diagonal elements.


Comments