Go language array slice

Array

Array: is the sequence of a fixed length of the same data type.

Array definition: var a [len] int, such as: var a [5] int

Length is the part of the array type, therefore, var a [5] int and var a [10] int different types

The array can be accessed by index, index starts from 0, the last element index is: len-1

for i := 0; i < len(a); i++ {
}

Access violation, if the array index is outside the legal range, triggering cross-border access, will panic

An array is a value type, so changing the value of a copy of itself does not change the value of

arr2 := arr1
arr2[2] = 100

 

You can not change the value of the array itself

package main

import (
	"fmt"
)

func modify(arr [5]int) {
	arr[0] = 100
	fmt.Println("arr",arr)
	return
}

func main() {
	var a [5]int

	modify(a)
	for i := 0; i < len(a); i++ {
		fmt.Println(a[i])
	}
}

  

Changing the value of the array pointer

main Package 

Import ( 
	"FMT" 
) 

FUNC Modify (ARR * [. 5] int) {// * [. 5] int values are represented need to pass the address 
	(* ARR) [0] = 100 
	fmt.Println ( "ARR" , ARR) 
	return 
} 

FUNC main () { 
	var A [. 5] int 

	Modify (& A) 
	for I: = 0; I <len (A); I ++ { 
		fmt.Println (A [I]) 
	} 
}

 

Array initialization  

age0 var [. 5] int = [. 5] {l, 2,3} int 

var AGE1 = [. 5] int {1,2,3,4,5} 

var Age2 = [...] {int l, 2,3, } 4,5,6 

var STR = [. 5] {String. 3: "Hello World",. 4: "Tom"} # specified value of a specific index

 

Multidimensional Arrays 

 

var age [5] [3] int // define an array of five rows and three columns 

var f [2] [3] int = [...] [3] int {{1, 2, 3}, {7, 8 , 9}} // define an array of two rows and three columns and initialize

 

  

 

Multidimensional array traversal

 

package main

import (
	"fmt"
)

func main() {

	var f [2][3]int = [...][3]int{{1, 2, 3}, {7, 8, 9}}

	for k1, v1 := range f {
		for k2, v2 := range v1 {
			fmt.Printf("(%d,%d)=%d ", k1, k2, v2)
		}
		fmt.Println()
	}
}

 

  

slice

 

 

  

 

Guess you like

Origin www.cnblogs.com/weidaijie/p/11429540.html