Golang study notes (iv) : array slice map

  • 2020-05-27 05:50:23
  • OfStack

1.Array

In the Go language, an array is a value type (value type)

All value type variables will generate a copy action when assigned and passed as arguments

If it is the parameter type of a function, the parameters are copied when the function is called, and the contents of the passed array cannot be modified in the body of the function

Array equality with =! = comparison, can't be used < >

1. The statement & The assignment

Initialize the

grammar


var VarName [n]type     // n>=0 e.g.
var a [5]int //[0 0 0 0 0]
var c [2][3]int //2 d var b int = [5]int{1,2,3,4,5} // Declare and initialize a := [3]int{1,2,3}
b := [10]int{1,2,3} // before 3 The other elements are 0
c := [20]int{19:1} // The first 20 All elements are initialized to zero 1 , other defaults 0
d := [...]int{4,5,6} // Automatic length calculation
e := [...]int{0:1, 1:2, 19:3} // Automatically inferring

2 d array


doubleArray := [2][4]int{[4]int{1,2,3,4}, [4]int{5,6,7,8}}
easyArray := [2][4]int{{1,2,3,4}, {1,2,3,4}}

Multidimensional [...]. [n] the former can be inferred, but the latter must display the assignment
The length of an array is one of the built-in constants for the array type

arrLength := len(arr)
Note that the array length is also part 1 of the type, so different length arrays are of different types (built-in constants)

That is, [3]int and [4]int are of different types, and the array cannot change length

The assignment between arrays is the assignment of values, that is, when an array is passed into a function as a parameter, a copy of the array (1 copy operation) is passed in, not its pointer. If you pass in a pointer, use slice

2. Element access


for i:=0; i < len(array); i++ {
    fmt.Println(i, array[i])
} for i, v := range array {
    fmt.Println(i, v)
}

You can create an array with new

p := new([10]int)

Returns a pointer to an array
Pay attention to distinguish between

Pointer to an array


a := [100]int{}
var p *[100]int = &a

Pointer to an array

x, y = 1, 2
a := [...]*int{&x, &y}

2.Slice

An array slice is like a pointer to an array, but it's more complex. It actually has its own data structure, not just a pointer (pointer to a native array + the number of elements in the array slice + the allocated storage space in the array slice).

1 reference type, always pointing to 1 underlying array, can be declared like array1, but no length is required

slice is like a structure with three elements

1 pointer to the starting position specified by slice in the array
The length, the length of slice
The maximum length, which is the length from the start of slice to the end of the array
1. The statement & The assignment

Created via array


var myArray [10]int = [10]int{1,2,3,4,5,6,7,8,9,10}
var mySlice []int = myArray[:5] a := [5]int{1,2,3,4,5}
b := a[2:4]
b := a[:4]
b := a[2:]

Declare again from an array or an existing slice

var ar [10]byte {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j'} var a, b []byte
a = ar[2:5]
b = ar[3:5]

Directly to create

myslice1 := make([]int, 5)
myslice2 := make([]int, 5, 10) // The initial number 5 Reserved, 10 The storage space of element
myslice3 := []int{1,2,3,4,5}

2. Element access


for i:=0; i<len(mySlice); i++ {
    fmt.Println(i, mySlice[i])
} for i, v := range mySlice {
    fmt.Println(i, v)
}

3. Other operations

Size and capacity

len gets the length of slice
cap gets the maximum capacity of slice

Add or subtract elements dynamically


append Want to slice In additional 1 Two or more elements, and then return 1 A and slice1 Sample types of slice //append
mySlice = append(mySlice, 1, 2, 3) // increase 3 An element
mySlice = append(mySlice, mySlice2) // To increase the other 1 a Pay attention to, append Will change slice The contents of the referenced array, affecting the reference system 1 The rest of the array slice .
     But when slice In which there is no space left, the new array space is dynamically allocated slice The array pointer is going to point to this space,
     While the contents of the original array will remain the same, other references to this array slice Is not affected ( Pits may be introduced bug)

copy


copy , from the source slice the src Copy to the target dst , and returns the number of copied elements
copy(dst, source) // I'm going to copy it in shorter Numbers slice1 := []int{1,2,3,4,5}
slice2 := []int{5,4,3} copy(slice2, slice1) // copy slice1 before 3 a 1 -> 2
copy(slice1, slice2) // copy slice2 The former 3 a 2 -> 1

slice


Default start position 0 . ar[:n] Is equivalent to ar[0:n]
The first 2 The default is array length ar[n:] Is equivalent to ar[n:len(ar)]
from 1 Get the array directly slice , can be ar[:]

slice is a reference type, so when you change an element in it, all other references change

aSlice = array[3:7]
bslice = aSlice[:3]

3.Map

The concept of a dictionary in Python

map is unordered and of variable length. The built-in len can be used for map and can be easily modified

1. The statement & The assignment


map[keyType]valueType var m map[string] PersonInfo
m = make(map[string] personInfo[, 100]) var numbers map[string]int
or
numbers := make(map[string]int)
numbers["one"] = 1

Initializes 1 dictionary

2. Element access


rating := map[string]float32 {"c":5, "Go":4.5} csharpRating, ok := rating["C#"]
if ok {
    fmt.Println("get the value")
} else{
    fmt.Println("error")
}

3. Basic operation

The assignment


m["1234"] = PersonInfo{}

delete

delete(m, "1234")

4. Other

make and new operations


doubleArray := [2][4]int{[4]int{1,2,3,4}, [4]int{5,6,7,8}}
easyArray := [2][4]int{{1,2,3,4}, {1,2,3,4}}
8

new is essentially like function 1 of the same name in other languages, new(T) allocates the memory space of type T filled with zero value, and returns its address, which is 1 *T value, which is 1 pointer to the zero value of the newly allocated type T

make(T, args), can only create slice,map,channel, and return an T type with an initial (non-zero) value, instead of *T. Essentially, what makes the three types different is that references to data structures must be initialized before they can be used


Related articles: