Go Example: Arrays

1. Introduction

An array is a collection of elements that are accessed by indexing and have a fixed size. They are useful when you need to store a fixed number of elements in a list. This blog post will cover the declaration, initialization, and usage of arrays in Go, including common operations such as iterating over elements and modifying them.

2. Program Steps

1. Declare an array with a specified type and size.

2. Initialize an array with values.

3. Access and modify the elements of the array.

4. Iterate over the array using a range-based loop.

5. Print the contents of the array.

3. Code Program

package main

import "fmt"

func main() {
	// Step 1: Declare an array that will hold exactly 5 ints
	var a [5]int
	fmt.Println("emp:", a)

	// Step 2: Initialize an array with values
	a[4] = 100
	fmt.Println("set:", a)
	fmt.Println("get:", a[4])

	// Step 3: Access and modify elements of the array
	// Get the length of the array
	fmt.Println("len:", len(a))

	// Step 4: Use range to iterate over the array
	for i, v := range a {
		fmt.Printf("Index: %d, Value: %d\n", i, v)
	}

	// Step 5: Declare and initialize an array in one line
	b := [5]int{1, 2, 3, 4, 5}
	fmt.Println("dcl:", b)
}

Output:

emp: [0 0 0 0 0]
set: [0 0 0 0 100]
get: 100
len: 5
Index: 0, Value: 0
Index: 1, Value: 0
Index: 2, Value: 0
Index: 3, Value: 0
Index: 4, Value: 100
dcl: [1 2 3 4 5]

Explanation:

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

2. import "fmt" - Imports the Format package for formatted I/O operations.

3. An array a is declared to hold five integers.

4. The emp: print statement shows the initial zero values of array a.

5. The array is then modified by setting the element at index 4 to 100.

6. set: and get: print statements demonstrate setting a value and retrieving a value from the array.

7. len(a) is used to print the length of the array.

8. A for loop with range is used to iterate over the array, printing each index and its corresponding value.

9. b is declared and initialized with values in a single line.

10. The dcl: print statement shows the initialized values of array b.

11. The output confirms the array's contents at each step of the demonstration.


Comments