Go language basic array

Posted by ppowell on Mon, 17 Jan 2022 06:05:12 +0100

This paper mainly introduces the array in Go language and its basic use.

An array is a collection of elements of the same data type. In Go language, the array is determined from the time of declaration. When used, the array members can be modified, but the array size cannot be changed. Basic syntax:

// Define an array a with a length of 3 and an element type of int
var a [3]int

Array definition:

var Array variable name [Number of elements]T

For example: var a [5]int, the length of the array must be constant, and the length is part of the array type. Once defined, the length cannot be changed. [5]int and [10]int are different types.

var a [3]int
var b [4]int
a = b //You can't do this because a and b are different types at this time

The array can be accessed by subscript. The subscript starts from 0. The subscript of the last element is len-1. If the access exceeds the boundary (the subscript is outside the legal range), the access exceeds the boundary and will panic.

Initialization of array

There are also many ways to initialize arrays.

Method 1

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

func main() {
	var testArray [3]int                        //The array is initialized to a zero value of type int
	var numArray = [3]int{1, 2}                 //Completes initialization with the specified initial value
	var cityArray = [3]string{"Beijing", "Shanghai", "Shenzhen"} //Completes initialization with the specified initial value
	fmt.Println(testArray)                      //[0 0 0]
	fmt.Println(numArray)                       //[1 2 0]
	fmt.Println(cityArray)                      //[Beijing, Shanghai, Shenzhen]
}

Method 2

According to the above method, ensure that the initial value provided is consistent with the length of the array every time. Generally, we can let the compiler infer the length of the array according to the number of initial values, for example:

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

Method 3

We can also initialize the array by specifying the index value, for example:

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

Traversal of array

There are two ways to traverse array a:

func main() {
	var a = [...]string{"Beijing", "Shanghai", "Shenzhen"}
	// Method 1: for loop traversal
	for i := 0; i < len(a); i++ {
		fmt.Println(a[i])
	}

	// Method 2: for range traversal
	for index, value := range a {
		fmt.Println(index, value)
	}
}

Multidimensional array

Go language supports multi-dimensional arrays. Here we take two-dimensional arrays as an example (arrays are nested in arrays).

Definition of two-dimensional array

func main() {
	a := [3][2]string{
		{"Beijing", "Shanghai"},
		{"Guangzhou", "Shenzhen"},
		{"Chengdu", "Chongqing"},
	}
	fmt.Println(a) //[[Beijing, Shanghai] [Guangzhou, Shenzhen] [Chengdu, Chongqing]]
	fmt.Println(a[2][1]) //Supported index value: Chongqing
}

Traversal of two-dimensional array

func main() {
	a := [3][2]string{
		{"Beijing", "Shanghai"},
		{"Guangzhou", "Shenzhen"},
		{"Chengdu", "Chongqing"},
	}
	for _, v1 := range a {
		for _, v2 := range v1 {
			fmt.Printf("%s\t", v2)
		}
		fmt.Println()
	}
}

Output:

Beijing	Shanghai	
Guangzhou	Shenzhen	
Chengdu	Chongqing	

Note: only the first layer of multidimensional array can be used To let the compiler deduce the array length. For example:

//Supported writing
a := [...][2]string{
	{"Beijing", "Shanghai"},
	{"Guangzhou", "Shenzhen"},
	{"Chengdu", "Chongqing"},
}
//Inner use of multidimensional arrays is not supported
b := [3][...]string{
	{"Beijing", "Shanghai"},
	{"Guangzhou", "Shenzhen"},
	{"Chengdu", "Chongqing"},
}

Array is a value type

An array is a value type. Assignment and transfer will copy the entire array. Therefore, changing the value of the copy will not change its own value.

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

func modifyArray2(x [3][2]int) {
	x[2][0] = 100
}
func main() {
	a := [3]int{10, 20, 30}
	modifyArray(a) //In modify, you modify the copy x of a
	fmt.Println(a) //[10 20 30]
	b := [3][2]int{
		{1, 1},
		{1, 1},
		{1, 1},
	}
	modifyArray2(b) //In modify, you modify the copy x of b
	fmt.Println(b)  //[[1 1] [1 1] [1 1]]
}

be careful:

  1. Array supports "= =", "! =" Operator, because memory is always initialized.
  2. [n]*T represents an array of pointers, * [n]T represents array pointers.

Exercises

  1. Find the sum of all elements of the array [1, 3, 5, 7, 8]
  2. Find the subscripts of the two elements in the array and the specified value. For example, find the subscripts of the two elements with sum 8 in the array [1, 3, 5, 7, 8], which are (0,3) and (1,2) respectively.

Topics: Go