Latest web development tutorials

Go language array

Go language provides an array of types of data structures.

An array is a set of data items have the same unique sequence number and type has a fixed length, which can be any type of primitive types such as plastic, string or a custom type.

With respect to the statement number0, number1, ..., and variables, use the array number99 of numbers [0], numbers [1] ..., numbers [99] is more convenient and easy to expand.

Array elements can be read by index (position) (or modify), an index from 0, the first element is index 0, the second an index of 1, and so on.


Declare an array

Go language element array declaration to specify the type and number of elements, the syntax is as follows:

var variable_name [SIZE] variable_type

The above is the definition of a one-dimensional array manner. And the length of the array must be an integer greater than 0. The following example defines an array of length 10 balance type float32:

var balance [10] float32

Array initialization

The following illustrates the array initialization:

var balance = [5]float32{1000.0, 2.0, 3.4, 7.0, 50.0}

The number of elements in the array initialization {} is not greater than [] in numbers.

If you ignore [] the numbers do not set the size of the array, Go language to set the size of the array will be based on the number of elements:

 var balance = []float32{1000.0, 2.0, 3.4, 7.0, 50.0}

This example is the same as with the example above, although the size of the array is not set.

 balance[4] = 50.0

The above examples read a fifth element. Array elements can be read by index (position) (or modify), an index from 0, the first element is index 0, the second an index of 1, and so on.


Access array elements

Array elements can be read by the index (position). Format for the value of the index after the array name with brackets, the brackets. E.g:

float32 salary = balance[9]

The above examples of the values ​​of the array balance reading the first 10 elements.

The following illustrates the complete array operations (declaration, assignment, access) examples:

package main

import "fmt"

func main() {
   var n [10]int /* n 是一个长度为 10 的数组 */
   var i,j int

   /* 为数组 n 初始化元素 */         
   for i = 0; i < 10; i++ {
      n[i] = i + 100 /* 设置元素为 i + 100 */
   }

   /* 输出每个数组元素的值 */
   for j = 0; j < 10; j++ {
      fmt.Printf("Element[%d] = %d\n", j, n[j] )
   }
}

The results of the above examples are as follows:

Element[0] = 100
Element[1] = 101
Element[2] = 102
Element[3] = 103
Element[4] = 104
Element[5] = 105
Element[6] = 106
Element[7] = 107
Element[8] = 108
Element[9] = 109

more content

Go to an array of language is very important, here we will introduce an array of more content:

content description
Multidimensional Arrays Go language support multi-dimensional arrays, multidimensional arrays are the simplest two-dimensional array
Passing arrays to functions You can pass an array as a function parameter