Go language provides an array type of data structure.
It is a fixed-length set of data items having the same unique data type, this may be any type of primitive types such as string, integer or another data type.
Array element can be read by the index (position) (or modified), the index starts from 0, the first element index is 0, the second index 1, and so on.
declaration of an array
The Go language array requires that you specify the element type and number of elements, the syntax is as follows:
var variable_name[SIZE] variable_type
Defined above is one-dimensional array. And the length of the array must be an integer greater than 0. The following example defines the length of the array 10 balance type float32:
var balance[10] float32
initialize an array
The following illustrates the array initialization:
var balance = [5] float32 {1000.0, 2.0, 3.4, 7.0, 50.0}
Initializes the number of elements in the array.
If the array size is not provided, Go will set the size of the array according to the number of elements:
var balance = [] float32 {1000.0, 2.0, 3.4, 7.0, 50.0}
This example is the same as above, although the size of the array is not provided.
balance[4] = 50.0
The above examples read the fifth element. Array element can be read by the index (position) (or modify), the index starts from 0, the first element index is 0, the second index 1, and so on.
access array elements
Array element can be read by the index (position). The format of the array name in square brackets, brackets in the value of the index. E.g:
float32 salary = balance[9]
The following illustrates the full array of operations (statement, assignment, access) examples:
package main
import "fmt"
func main () {
var n[10] int /* n is a length of the array 10 */
var i, j int
/* Initialize an array element n */
for i = 0; i <10; i ++ {
n[i] = i + 100 /* set elements i + 100 */
}
/* Output value of each array element */
for j = 0; j <10; j ++ {
fmt.Printf( "Element [%d] = %d \n", j, n[j])
}
}
Examples of the implementation of the above results 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 array of language is very important, we will introduce an array of more of the following elements:
Content | Description |
---|---|
Multidimensional array | Go language support multidimensional arrays, multidimensional arrays are the simplest two-dimensional array |
Pass an array to function | You can pass an array parameter as a function |
Top comments (0)