Array Operations in Software Development

GolangGolangBeginner
Practice Now

Introduction

In modern software development, we often need to store a large amount of data.

Based on what we have learned, we can easily define dozens of variables.

But if we need to use variables to record the names of employees in a company, with data on a scale of hundreds or thousands, do we have to define them one by one?

Of course not. For data with similar attributes, we can use arrays to define and store them.

We can think of arrays as a group of variables that come together like a train. And when we want to find a specific variable, we just need to know the train number (array name) and the seat number (index). Then we can find and manipulate the variable without knowing its name.

In this section, we will learn about various basic operations of arrays.

Knowledge Points:

  • Array definition
  • Array initialization
  • Array traversal
  • Characteristics of array values

Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL go(("`Golang`")) -.-> go/BasicsGroup(["`Basics`"]) go(("`Golang`")) -.-> go/FunctionsandControlFlowGroup(["`Functions and Control Flow`"]) go(("`Golang`")) -.-> go/ObjectOrientedProgrammingGroup(["`Object-Oriented Programming`"]) go/BasicsGroup -.-> go/variables("`Variables`") go/FunctionsandControlFlowGroup -.-> go/for("`For`") go/FunctionsandControlFlowGroup -.-> go/range("`Range`") go/FunctionsandControlFlowGroup -.-> go/functions("`Functions`") go/ObjectOrientedProgrammingGroup -.-> go/struct_embedding("`Struct Embedding`") subgraph Lab Skills go/variables -.-> lab-149075{{"`Array Operations in Software Development`"}} go/for -.-> lab-149075{{"`Array Operations in Software Development`"}} go/range -.-> lab-149075{{"`Array Operations in Software Development`"}} go/functions -.-> lab-149075{{"`Array Operations in Software Development`"}} go/struct_embedding -.-> lab-149075{{"`Array Operations in Software Development`"}} end

Array Definition

How do we define an array?

Let's recall the situation when we learned about variables. How did we define an int variable?

var a int

That is:

var variable_name variable_type

Similarly, we can define an int array like this:

var a [10]int

That is:

var variable_name [number_of_elements]variable_type

In this way, we have defined a basic int array called a with a capacity of 10.

Initialization List

After understanding how to define an array, let's learn how to initialize an array.

When initializing an array, we can use an initialization list to set the initial values of the array elements.

Create a array.go file in the ~/project directory:

touch ~/project/array.go

Write the following code in array.go:

package main

import "fmt"

func main() {
    // Automatically initialized to 0
    var simpleArray [3]int
    // Initialize with specified initial values, and use default values to fill in the missing elements
    var numArray = [3]int{1, 2}
    // Initialize with specified initial values
    var cityArray = [2]string{"Hangzhou", "Chengdu"}
    fmt.Println(simpleArray) // [0 0 0]
    fmt.Println(numArray)    // [1 2 0]
    fmt.Println(cityArray)   // [Hangzhou Chengdu]
}

The output will be:

[0 0 0]
[1 2 0]
[Hangzhou Chengdu]

The above code demonstrates three ways to specify initial values using an initialization list:

  • Without passing a list: Initialize to the default initialization value of the element type
  • Passing a partial list: Initialize the specified elements with the specified values, and initialize the remaining elements to the default value
  • Passing a complete list: Initialize with the specified values

Note that if the length of the list passed in is greater than the number of elements in the array, the code will not compile.

Inferred Length Initialization

When initializing an array using an initialization list, we must ensure that the number of initial values provided is less than or equal to the number of elements.

In general, we can rely on the compiler to infer the array length based on the initial values.

Write the following code in array.go:

package main

import "fmt"

func main() {
    var simpleArray [3]int
    var numArray = [...]int{1, 2}
    var cityArray = [...]string{"Hangzhou", "Chengdu"}
    fmt.Println(simpleArray)                      // [0 0 0]
    fmt.Println(numArray)                         // [1 2]
    fmt.Printf("The type of numArray is: %T\n", numArray)   // The type of numArray is: [2]int
    fmt.Println(cityArray)                        // [Beijing Shanghai Shenzhen]
    fmt.Printf("The type of cityArray is: %T\n", cityArray) // The type of cityArray is: [3]string
}

The output will be:

[0 0 0]
[1 2]
The type of numArray is: [2]int
[Hangzhou Chengdu]
The type of cityArray is: [2]string

The above code demonstrates how to initialize an array by inferring the length from the initial values.

Initialization with Specified Index

Sometimes, we may want to assign specific initial values to certain positions in an array, regardless of whether we use an initialization list or infer the length.

Then, we can use initialization with specified indices.

Write the following code in array.go:

package main

import "fmt"

func main() {
    a := [...]int{1: 1, 3: 5}
    fmt.Println(a)                  // [0 1 0 5]
    fmt.Printf("The type of array a is: %T\n", a) // The type of array a is: [4]int
}

The output will be:

[0 1 0 5]
The type of array a is: [4]int

The above code specifies the initial values of the elements with indices 1 and 3 as 1 and 5, respectively. It also uses the inference of length initialization method, which you should learn.

Note: In computing, the index starts from 0.

Array Traversal

Sometimes, we need to access each element of an array and perform operations on them one by one.

Here, we introduce two ways to traverse arrays:

Write the following code in array.go:

package main

import "fmt"

func main() {
    a := [...]int{123, 321, 456, 777}
    // Method 1: range
    fmt.Println("Traversing the array using range")
    for index, value := range a {
        fmt.Println(index, " ", value)
    }
    // Method 2: using indices
    fmt.Println("\nTraversing the array using indices")
    for i := 0; i < len(a); i++ {
        fmt.Println(a[i])
    }
}

The output will be:

Traversing the array using range
0 123
1 321
2 456
3 777

Traversing the array using indices
123
321
456
777

Both methods above can be used to traverse the entire array.

Accessing Array Elements

To access a specific number in an array, which is essentially a variable, we use the index.

Similar to most programming languages, the index of an array starts from 0, and the index of the last element is len-1.

If an index larger than this limit is used in the code, it will result in an out-of-bounds error.

To access the i-th element of the a array, you can use the following notation:

a[i]

That is:

array_name[index_of_element]

Value Type of Arrays

Arrays are value types; assigning an array or passing an array as a parameter will copy the entire array. In other words, we will modify the values of the copy, not the original array.

Write the following code in array.go:

package main

import "fmt"

func modifyArray(x [3]int) {
    x[0] = 100
}

func main() {
    a := [3]int{10, 20, 30}
    modifyArray(a) // The variable `x` in `modifyArray` is a copy of `a`
    fmt.Println(a) // [10 20 30]
}

The output will be:

[10 20 30]

From the above code, it can be seen that when the a array is passed to the modifyArray function, only a copy of its original array is actually passed.

Changing the value of array x in the function does not affect the original array a.

Summary

In this lab, we learned:

  • How to define an array
  • Three methods of array initialization
  • Characteristics of arrays and how to access elements

Arrays are not commonly used in actual development, but they are the basis for learning commonly used data structures in Go.

I hope that all Gophers can practice diligently and learn to apply what they have learned.

In the next section, we will learn about multi-dimensional arrays.

Other Golang Tutorials you may like