SoFunction
Updated on 2025-03-05

Golang study notes (IV): array, slice, map

1.Array

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

All value type variables will produce a copy action when assigned and passed as parameters.

If it is a parameter type of a function, data copying occurs when the parameter is called, and the contents of the passed array cannot be modified in the function body.

Use = != to compare arrays, not < >

1. Declaration & Assignment

initialization

grammar

Copy the codeThe code is as follows:

var VarName [n]type     // n>=0

.
var a [5]int //[0 0 0 0 0]
var c [2][3]int //Two-dimensional

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} //The first three elements, the others are 0
c := [20]int{19:1} //The 20th element is initialized to 1, and the other defaults to 0
d := [...]int{4,5,6} //Calculate the length automatically
e := [...]int{0:1, 1:2, 19:3} //Automatic inference

Two-dimensional array

Copy the codeThe code is as follows:

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 assignments
The length of the array is a built-in constant for the array type

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

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

The assignment between arrays is the assignment of value, that is, when an array is passed into a function as a parameter, the passed in is actually a copy of the array (a copy operation) rather than its pointer. If you want to pass in a pointer, use slice.

2. Element access

Copy the codeThe code is as follows:

for i:=0; i < len(array); i++ {
    (i, array[i])
}

for i, v := range array {
    (i, v)
}


You can create an array with new
Copy the codeThe code is as follows:

p := new([10]int)

Return a pointer to an array
Pay attention to the distinction

Pointer to an array

Copy the codeThe code is as follows:

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

Pointer array
Copy the codeThe code is as follows:

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

2.Slice

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

A reference type always points to an underlying array, and declares that it can be like an array, but does not require length

slice is like a structure containing three elements

A pointer pointing to the starting position specified by slice in the array
length, that is, the length of slice
The maximum length, that is, the length from the start position of the slice to the last position of the array
1. Declaration & Assignment

Created through array

Copy the codeThe code is as follows:

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 it again from an array or an existing slice
Copy the codeThe code is as follows:

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]


Create directly
Copy the codeThe code is as follows:

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

2. Element access

Copy the codeThe code is as follows:

for i:=0; i<len(mySlice); i++ {
    (i, mySlice[i])
}

for i, v := range mySlice {
    (i, v)
}

3. Other operations

Size and capacity

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

Dynamic addition and decreasing elements

Copy the codeThe code is as follows:

Append wants to add one or more elements into the slice, and then return a slice of the same type as slice.

//append
mySlice = append(mySlice, 1, 2, 3) //Add three elements
mySlice = append(mySlice, mySlice2) //Add another

Note that append will change the content of the array referenced by the slice, thereby affecting other slices that reference the unified array.
But when there is no remaining space in the slice, the slice array pointer returned by dynamically allocating the new array space will point to this space.
The content of the original array will remain unchanged, and other slices referencing this array will not be affected (pit, bugs may be introduced)

Content copy

Copy the codeThe code is as follows:

copy, copy from the src of the source slice to the target dst, and returns the number of copied elements
copy(dst, source) //It will be copied by a short number of

slice1 := []int{1,2,3,4,5}
slice2 := []int{5,4,3}

copy(slice2, slice1) //Copy the first three slice1 1 -> 2
copy(slice1, slice2) //Copy the first three of slice2 2 -> 1

slice

Copy the codeThe code is as follows:

The default start position is 0, ar[:n] is equivalent to ar[0:n]
The second sequence is the array length ar[n:] by default, which is equivalent to ar[n:len(ar)]
Get slice directly from an array, which can be ar[:]

slice is a reference type, so when changing the element, all other references will change
Copy the codeThe code is as follows:

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

3.Map

The concept of dictionary in Python

Map is disordered and has no fixed length. The built-in len can be used for maps and can be easily modified

1. Declaration & Assignment

Copy the codeThe code is as follows:

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


Initialize a dictionary

2. Element access

Copy the codeThe code is as follows:

rating := map[string]float32 {"c":5, "Go":4.5}

csharpRating, ok := rating["C#"]
if ok {
    ("get the value")
} else{
    ("error")
}


3. Basic operations

Assignment

Copy the codeThe code is as follows:

m["1234"] = PersonInfo{}

delete
Copy the codeThe code is as follows:

delete(m, "1234")

4. Others

Make and new operations

Copy the codeThe code is as follows:

make is used for memory allocation of built-in types (map, slice, channel).

new is used for various types of memory allocation

new is essentially the same as the same name function in other languages. new(T) allocates the memory space of T type filled with zero value and returns its address, that is, a value of type *T, that is, it returns a pointer to point to the zero value of the newly allocated type T.

make(T, args), can only create slice, map, channel, and return a T type with an initial value (non-zero value), not *T. Essentially, the reason why these three types are different is that references to data structures must be initialized before use