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 numerous variables.
However, 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 collection 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 elements
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 an array.go file in the ~/project directory:
cd ~/project
touch array.go
Write the following code in array.go:
package main
import "fmt"
func main() {
// Automatically initialized to the zero value of the element type
var simpleArray [3]int
// Initialize with specified initial values, and use the zero value to fill in the missing elements
var numArray = [3]int{1, 2}
// Initialize with specified initial values
var cityArray = [2]string{"London", "Chengdu"}
fmt.Println(simpleArray) // [0 0 0]
fmt.Println(numArray) // [1 2 0]
fmt.Println(cityArray) // [London Chengdu]
}
Run the code:
go run ~/project/array.go
Expected output:
[0 0 0]
[1 2 0]
[London Chengdu]
The above code demonstrates three ways to specify initial values using an initialization list:
- Without passing a list: Initialize to the zero value of the element type
- Passing a partial list: Initialize the specified elements with the specified values, and initialize the remaining elements to the zero 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, you must ensure that the number of initial values provided is less than or equal to the number of elements.
In general, you can rely on the compiler to infer the array length based on the initial values.
Modify the array.go file as follows:
package main
import "fmt"
func main() {
var simpleArray [3]int
var numArray = [...]int{1, 2}
var cityArray = [...]string{"London", "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) // [London Chengdu]
fmt.Printf("The type of cityArray is: %T\n", cityArray) // The type of cityArray is: [2]string
}
Run the code:
go run ~/project/array.go
Expected output:
[0 0 0]
[1 2]
The type of numArray is: [2]int
[London Chengdu]
The type of cityArray is: [2]string
Initialization with Specified Indices
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.
Modify the array.go file as follows:
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
}
Run the code:
go run ~/project/array.go
Expected output:
[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])
}
}
Run the code:
go run ~/project/array.go
Expected output:
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 element 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, you 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]
}
Run the code:
go run ~/project/array.go
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 the 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 their elements
Arrays are not commonly used in actual development, but they are the foundation for learning commonly used data structures in Go.
I hope that all Gophers will practice diligently and learn to apply what they have learned.



