Built-in function
// 1. close: mainly used to turn off channel // 2. len: For length, such as string, array, slice, map, channel // 3. new: Used to allocate memory, mainly for value types, such as int, struct.Return is pointer // 4. make: Used to allocate memory, mainly to allocate reference types such as chan, map, slice // 5. append: used to append elements to arrays, slice s
Examples are as follows:
// new Example: package main import "fmt" func main(){ var i int fmt.Println(i) j := new(int) fmt.Println(j) *j = 100 fmt.Println(*j) } // The results are as follows: [root@NEO example01_new]# go run main/main.go 0 0xc0000160b0 100 [root@NEO example01_new]# // append Example: package main import "fmt" func main(){ var a []int // [] Writing no numbers means a slice slice a = append(a,1,2) // append Medium is also a variable parameter fmt.Println(a) a = append(a,a...) // Add a slice; a...Represents a slice a All elements in fmt.Println(a) } // The results are as follows: [root@NEO example01_append]# go run main/main.go [1 2] [1 2 1 2] [root@NEO example01_append]# // recover Example: package main import "fmt" func test(){ defer func(){ // func(){} Is an anonymous function; func(){...}() Execute anonymous functions if err := recover(); err != nil{ // recover() Is Catching Exceptions fmt.Println(err) } }() a := 0 b := 1/a fmt.Println(b) return } func main(){ test() fmt.Println("hello world") } // The results are as follows: [root@NEO example01_recover]# go run main/main.go runtime error: integer divide by zero hello world [root@NEO example01_recover]#
Recursive function
A function that calls itself is called recursion.The sample code is as follows:
// Example code 1: package main import ( "fmt" ) func calc(n int) int { if n == 1 { return 1 } return calc(n-1) * n } func main() { n := calc(5) fmt.Println(n) } // Example 2: Fibonacci number package main import "fmt" func fab(n int) int { if n <= 1 { return 1 } return fab(n-1)+fab(n-2) } func main(){ n := fab(10) fmt.Println(n) }
Recursive design principles
1) A large problem can be broken down into similar small problems 2) Define Export Conditions
closure
Closure: An entity that is a combination of a function and its associated reference environment.Examples are as follows:
// Sample code: package main import "fmt" func Adder() func(int) int { // function Adder The return value of is also a function var x int return func(d int) int { // Where return To the return value type defined above return Same function as x += d return x } } func main() { f := Adder() // f Is a function fmt.Println("f(1)",f(1)) // here x The default value is 0 fmt.Println("f(10)",f(10)) // here x The value becomes 1 fmt.Println("f(100)",f(100)) // here x The value becomes 10 } // The results are as follows: [root@NEO example03_closure]# go run main/main.go f(1) 1 f(10) 11 f(100) 111 [root@NEO example03_closure]#
Arrays and Slices
// 1. Array: A fixed-length sequence of the same data type. // 2. Array definition: var a [len]int,For example: var a[5]int,Once defined, the length cannot be changed; the element defaults to 0 // 3. Length is part of the array type, so, var a[5] int and var a[10]int Different types // 4. Arrays can be accessed through subscripts, which start with 0 and end with: len-1 for i := 0; i < len(a); i++ { } for index, v := range a { } // 5. Access beyond bounds, if subscripts are outside the bounds of combinatorial methods, trigger access beyond bounds, and panic // 6. Arrays are value types, so changing the value of a copy does not change its own value arr2 := arr1 arr2[2] = 100
Initialization of arrays
1. var age0 [5]int = [5]int{1,2,3} // Initialize when defined 2. var age1 = [5]int{1,2,3,4,5} 3. var age2 = [...]int{1,2,3,4,5,6} // ... What it does: The compiler will automatically help you count the number of elements, then the length of the array 4. var str = [5]string{3:"hello world", 4:"tom"} // Specify the element corresponding to the subscript when defining
Multidimensional Array
1. var age [5][3]int // Two-dimensional array: 5 rows and 3 columns 2. var f [2][3]int = [...][3]int{{1, 2, 3}, {7, 8, 9}} // ... Indicates how many lines the compiler counts itself
Multidimensional Array Traversal
// Sample code: package main import "fmt" func test(){ var arr [2][5]int = [...][5]int{{1,2,3,4,5},{6,7,8,9,10}} for row,v_row := range arr{ for col,v_col := range v_row { fmt.Printf("(%d,%d)=%d ",row,col,v_col) } fmt.Println() } } func main(){ test() } // The results are as follows: [root@NEO example04_multi_dim_arr]# go run main/main.go (0,0)=1 (0,1)=2 (0,2)=3 (0,3)=4 (0,4)=5 (1,0)=6 (1,1)=7 (1,2)=8 (1,3)=9 (1,4)=10 [root@NEO example04_multi_dim_arr]#
Section
// 1.Slice: A slice is a reference to an array, so the slice is a reference type; if you pass a slice into a function to modify the value of an element in the slice, the value of the slice outside the function will change, and the array will not. // 2. The length of the slice can change, so the slice is a variable array // 3. Slices are traversed in the same way as arrays and can be len() for length // 4. cap can find the maximum slice capacity, 0 <= len (slice) <= cap (array), where array is the array referenced by slice // 5. Definition of slices: var variable name [] type, such as var str []string and var arr []int (this way slices are defined, but slices are not initialized, so arr[0]=1 cannot be assigned directly at this time)
Examples are as follows:
// Slices are examples of reference types 1: package main import "fmt" func modifySlice(a []int){ // The parameter to be passed in for this function is the slice type; slice map and chan Type parameters pass in the address a[1] = 100 // Modify Slices a After the value of the element, outside the function a The value of will also change } func testSlice(){ var s []int = []int{1,2,3} modifySlice(s) // A slice is a reference type and is a reference to an array (which can be interpreted as a slice being an address); this function passes a reference (the reference contains a pointer); and this function passes an address fmt.Println(s) } func main(){ testSlice() } // The results are as follows: [root@NEO example05_slice_ref_type]# go run main/main.go [1 100 3] // The value of the out-of-function slice also changes [root@NEO example05_slice_ref_type]# // Slices are examples of reference types 2: package main import "fmt" func testSliceRefArr(){ var a = [10]int{1,2,3} // Declare and initialize an array b := a[1:4] // Declare and initialize a slice fmt.Printf("%p\n",b) // %p Represents a hexadecimal representation that can be used to print an address fmt.Printf("%p\n",&a[1]) // array a Address of the first element } func main(){ testSliceRefArr() } // The results are as follows: [root@NEO example05_slice_ref_arr]# go run main/main.go 0xc000064008 0xc000064008 // Section b Addresses and Arrays a The address of the first element is the same; therefore, the slice is an address [root@NEO example05_slice_ref_arr]# // Sample code: package main import "fmt" func testSlice(){ var slice []int // Declare an array; simply define the array, but do not initialize the slice, so it cannot be directly done at this time arr[0]=1 This assignment var arr [5]int = [...]int{1,2,3,4,5} // Declare and initialize an array slice = arr[2:5] // Initialization of slices; careless; abbreviated as arr[2:] fmt.Println(slice) fmt.Println("len:",len(slice)) fmt.Println("cap:",cap(slice)) slice = slice[0:1] fmt.Println("len:",len(slice)) fmt.Println("cap:",cap(slice)) } func main(){ testSlice() } // slice,map,channel All available make To initialize // The results are as follows: [root@NEO example05_slice01]# go run main/main.go [3 4 5] len: 3 cap: 3 len: 1 cap: 3 [root@NEO example05_slice01]#
Slice creation method 1: creating from an array
// 1. Slice initialization: var slice []int = arr[start:end] ;Contain start reach end Between elements, but without end // 2. var slice []int = arr[0:end]Can be abbreviated as var slice []int=arr[:end] // 3. var slice []int = arr[start:len(arr)] Can be abbreviated as var slice[]int = arr[start:] // 4. Var slice []int = arr[0, len(arr)] Can be abbreviated as var slice[]int = arr[:] // 5. If you want to remove the last element of the slice, you can write as follows: Slice = slice[:len(slice)-1]
Slice creation method 2: Create slices by making
var slice []type = make([]type, len) slice := make([]type, len) slice := make([]type, len, cap)
Using append built-in function to manipulate slices
// Example: slice = append(slice, 10) var a = []int{1,2,3} var b = []int{4,5,6} a = append(a, b...) // b... Represents a slice b All elements in // append Example: package main import "fmt" func testSlice(){ var a [5]int = [...]int{1,2,3,4,5} b := a[1:] fmt.Printf("b=%p a[1]=%p\n",b,&a[1]) // Slice at this time b Addresses and Arrays a The address of the first element is the same b[1] = 100 fmt.Println("before a:",a) // Change slice at this time b Array of values for a Will also change b = append(b,10) b = append(b,10) b = append(b,10) b = append(b,10) b = append(b,10) b = append(b,10) // After adding five elements, you've exceeded the slice b Capacity of fmt.Println(b) fmt.Printf("b=%p a[1]=%p\n",b,&a[1]) // Slice at this time b Addresses and Arrays a The address of the first element is no longer the same; because the slice is declared and defined b No more than b Capacity, at this time b Points to the original array when more than b After capacity of, the system will reclaim a piece of memory and slice b Place the original value in the newly opened memory, then put the appended content in b[1] = 1000 fmt.Println("after a:",a) // Change at this time b Value, a The value of will not change because the slice b The memory address pointed to is no longer a Yes } func main(){ testSlice() // Slices are variable because internal memory is reallocated according to capacity } // The results are as follows: [root@NEO example05_slice_beyond_cap]# go run main/main.go b=0xc000014158 a[1]=0xc000014158 before a: [1 2 100 4 5] // a The corresponding values have also changed [2 100 4 5 10 10 10 10 10 10] b=0xc000062080 a[1]=0xc000014158 after a: [1 2 100 4 5] // here a The value in does not change [root@NEO example05_slice_beyond_cap]#
Slice resize
var a = []int {1,3,4,5} b := a[1:2] b = b[0:3]
Slice copy: copy()
s1 := []int{1,2,3,4,5} s2 := make([]int, 10) copy(s2, s1) // Slice s1 Copy to Slice s2 Medium; copies will not be expanded // Sample code: package main import "fmt" func testCopy(){ var a []int = []int{1,2,3,4,5} b := make([]int,10) c := make([]int,1) copy(b,a) // hold a copy to b in copy(c,a) // hold a copy to c in fmt.Println(b) fmt.Println(c) // Copies will not be expanded } func main(){ testCopy() } // The results are as follows: [root@NEO example05_slice_copy]# go run main/main.go [1 2 3 4 5 0 0 0 0 0] [1] [root@NEO example05_slice_copy]#
An example of a slice: a non-recursive implementation of the Fibonacci series, printing the first 10 numbers.
// The sample code is as follows: package main import "fmt" func fab(n int){ var a []int // Declare a slice;[]There are no numbers in it, so it's a slice a = make([]int,n) // For slicing a Allocate memory a[0] = 1 a[1] = 1 for i := 2; i < len(a); i++ { a[i] = a[i-1] + a[i-2] } for _,v := range a{ fmt.Println(v) } } func main() { fab(10) } // The results are as follows: [root@NEO example04_fab_slice]# go run main/main.go 1 1 2 3 5 8 13 21 34 55 [root@NEO example04_fab_slice]#