Slice slice
Like an array, a slice represents a continuous collection of multiple elements of the same type, but the slice itself does not store any elements, but only a reference to an existing array.
The slice structure includes address, length and capacity.
- Address: the address of the slice generally refers to the memory address pointed to by the first element in the slice, expressed in hexadecimal.
- Length: the number of elements that actually exist in the slice.
- Capacity: the number from the starting element of the slice to the last element in its underlying array.
The length and capacity of the slice are not fixed. You can increase the length and capacity of the slice by adding elements.
There are three main ways to generate slices:
- Generate a new slice from the array.
- Generate a new slice from the slice.
- Generate a new slice directly.
Generate a new slice from the array
package main import ( "fmt" ) func main() { var student = [...]string{"Tom", "Ben", "Peter"} var student1 = student[0:2] fmt.Println("student Array:", student) fmt.Println("student1 section:", student1) fmt.Println("student The array address is:", &student[0]) fmt.Println("student1 The slice address is:", &student1[0]) fmt.Println("student1 Slice length:", len(student1)) fmt.Println("student1 Slice capacity:", cap(student1)) }
Running the above code, we can find:
- Newly generated slice length = end position - start position
- The elements extracted from the newly generated slice do not include the elements corresponding to the end position (closed on the left and open on the right).
- The newly generated slice is a reference to an existing array or slice, and its address is the same as the element address corresponding to the start position of the intercepted array or slice.
- The newly generated slice capacity refers to the number from the start element of the slice to the last element in its underlying array.
Generate a new slice directly
-
Declaration slice
Declaration format of slice:
var slice variable name [] element type
After the slice is declared, its content is empty, and its length and capacity are 0.
-
Initialize slice
-
Initialize while declaring
var student = []string{"Tom", "Ben", "Peter"}
-
Initialize with the make() function
After declaring the slice, you can initialize the slice through the built-in function make(). The format is as follows:
slice = make ([]Element type, Slice length, Slice capacity)
The capacity of the slice should be estimated roughly. If the capacity is too small, multiple expansion of the slice will cause performance loss.
-
-
Adding elements to slices
In Go language, we can use the append () function to add elements to the slice. When the slice length value is equal to the capacity value, the next time you use the append() function to add elements to the slice, the capacity will be expanded by 2.
func main() { student := make([]int, 1, 1) for i := 0; i < 8; i++ { student = append(student, i) fmt.Println("Length of current slice:", len(student),"Current slice capacity:", cap(student)) } }
-
Delete element from slice
Because the Go language does not provide a method for deleting slice elements, we need to manually connect the elements before and after the deletion point to delete the elements in the slice.
func main() { var student = []string{"Tom", "Ben", "Peter", "Danny"} student = append(student[0:1], student[2:]...) //student = student[0:0] Empty all elements in the slice fmt.Println("student section:", student) fmt.Println("student Slice length:", len(student)) fmt.Println("student Slice capacity:", cap(student)) }
The ellipsis passed in the append() function represents expansion by student slice, which is equivalent to:
student = append(student[0:1], student[2], student[3])
Clearing all elements in the slice can be achieved by setting the start and end subscripts of the slice to 0.
Map map
A map is an unordered collection of key value pairs. The key of a map is similar to an index and points to the value of data.
-
Declaration mapping
The declaration format of map is as follows:
var map [Key type]Value type
-
Initialize mapping
-
Initialize while declaring
func main() { var studentScoreMap = map[string]int { "Tom" : 80, "Ben" : 85, "Peter" : 90, } fmt.Println(studentScoreMap) // map[Ben:85 Peter:90 Tom:80] }
-
Initialize with the make() function
The format is as follows:
make(map[Key type]Value type, map capacity)
When using the make() function to initialize, you can not specify the map capacity, but multiple expansion of the map will cause performance loss.
-
-
Remove key value pairs from mapping
Go language deletes the specified key value pair of map through the delete() function. The format is as follows:
delete(map example, key)
In addition, the Go language does not provide a method to empty all elements for a map. The only way to empty a map is to redefine a new map.
package main import "fmt" func main() { var studentScoreMap map[string]int studentScoreMap = make(map[string]int) studentScoreMap["Tom"] = 80 studentScoreMap["Ben"] = 70 studentScoreMap["Peter"] = 90 delete(studentScoreMap, "Tom") fmt.Println(studentScoreMap) // map[Ben:70 Peter:90] }
function
Features supported by Go language functions:
- The number of parameters is not fixed (variable parameters).
- Anonymous functions and closures.
- The function itself is passed as a value.
- Delayed execution of function.
- Call the function as an interface.
Declarative function
The format is as follows:
func Function name (parameter list) (return parameter list) { Function body }
-
In the parameter list, if the adjacent variables are of the same type, it is not necessary to write out the type repeatedly.
func add(x, y int) (sum int) { sum = x + y return sum }
-
If the return values of the function are of the same type, the return parameters can be omitted from the return value list.
func returnValue() (int, int) { return 0, 1 }// This writing method is not recommended. The readability of the code is reduced and the actual meaning of each return value cannot be distinguished.
Function variable
In Go language, function is also a type, and we can save it in variables.
var Variable name func()
package main import "fmt" func addSub(x int, y int) (sum int, sub int) { sum = x + y sub = x - y return sum, sub } func main() { a := 1 b := 2 f1 := addSub //Or var f1 func(x int, y int) (sum int, sub int) //f1 = addSub sum, sub := f1(a, b) fmt.Println(a, "+", b, "=", sum) fmt.Println(a, "-", b, "=", sub) }
Function variables can be declared and initialized in short variable format.
Or, after the function variable f1 is declared, its value is initialized to nil, and then the addSub function is assigned to f1. All calls to f1 are calls to the addSub function.
Unfinished