Go function, array, pointer, structure, slice
10, Functions
1. Format:
func Function name(parameter list) return type{ } When there are multiple return values: func Function name(parameter list) (Return value 1 type,Return value 2 type,Return value 3 type){ }
2. Function parameters
(1) Value passing; Go language uses value passing by default
(2) Reference passing: x *int
3. Function as argument
Example:
//Declare function variables getSquareRoot := func(x float64) float64 { return math.Sqrt(x) } /* Use function */ fmt.Println(getSquareRoot(9))
4. Closure (anonymous function)
Example:
func get1() func() int { i :=0 return func() int { i++ return i } } func get2(x,y int) func(a,b int) (int,int){ return func(a, b int) (int, int) { return x+y,a+b } } func main(){ nextNum := get1() println(nextNum()) sumNum := get2(1,2) println(sumNum(3,4)) }
5. Method
There are both functions and methods in Go language. A method is a function that contains a receiver, which can be a value or a pointer of a named type or struct type. All methods of a given type belong to the set of methods of that type.
Format:
func (variable_name variable_data_type) function_name() [return_type]{ /* Function body*/ }
Example:
type Circle struct { radius float64 } func (c Circle) area() float64 { return 3.14*c.radius*c.radius } func main(){ var c1 Circle c1.radius=10 println(c1.area()) }
11, Variable scope
12, Array
1. Format
var Array name [Array size] data type
Example: var a [10] int
2. Initialization
Example:
var a = [3]int{1,2,3} //perhaps a := [3]int{1,2,3}
(1) If the length of the array is uncertain, you can use... Instead of the length of the array. The compiler will infer the length of the array according to the number of elements
Example: var a = [...]int{1,2,3,4,5}
(2) If the length of the array is set, you can also initialize elements by specifying subscripts
// Initializes elements with indexes 1 and 3 a := [5]float32{1:2.0,3:7.0}
2. Multidimensional array
var Array name [1 Dimension array size][2 Dimension array size]...[n Dimension array size] data type
Example: var a [2][3]int
3. Instance
//array var a [5]int for i :=0;i<5;i++ { a[i]=i+1 } for j :=0;j<5;j++ { println(a[j]) } b1 := [3]float32{1.0,2.0,3.0} for i :=0;i<3;i++ { println(b1[i]) } b2 := [...]int{1,2,3} for j :=0;j<3;j++ { println(b2[j]) } b3 := [5]int{0:2,3:6} for k :=0; k<5;k++ { println(b3[k]) } //Two dimensional array values := [][]int{} row1 := []int{1,2,3} row2 := []int{4,5,6} values = append(values, row1) values = append(values,row2) fmt.Println("Row1:",values[0]) fmt.Println("Row2:",values[1]) fmt.Println("The first element is:",values[0][0]) a := [3][4]int{ {0, 1, 2, 3} , /* The first row index is 0 */ {4, 5, 6, 7} , /* The index of the second row is 1 */ {8, 9, 10, 11}, /* The third row has an index of 2 */ } fmt.Println(a[0]) str := [2][2]string{} str[0][0] ="a" str[1][1] ="b" fmt.Println(str) animals := [][]string{} row1 := []string{"dog","cat","fish"} row2 := []string{"bird","shark"} row3 := []string{"sheep"} animals =append(animals,row1) animals =append(animals,row3) animals =append(animals,row2) for i := range animals{ fmt.Println(animals[i]) }
13, Pointer
Format:
var Pointer name *Pointer type
1. Null pointer
When a pointer is defined and not assigned to any variable, its value is nil. Nil conceptually, like null, None, nil and null in other languages, refers to zero value or null value
2. Example:
var ptr *int var a int = 10 ptr = &a
3. Pointer array
Format:
var Pointer name [Pointer size]*Pointer type
4. Pointer to pointer
Format:
var Pointer name **Pointer type
14, Structure
1. Structure
A structure is a data set composed of a series of data of the same type or different types
Format:
type Structure name struct{ Variable name variable type ... Variable name variable type }
2. Define structure type variables
var Variable name structure name or Variable name:= Structure name{value1,value2,...,valuen} or Variable name:= Structure name{key1:value1,key2:value2,...,keyn:valuen}
3. Assign values to variables in the structure
Structure variable name Structure internal variable = value
4. Instance
type Book struct { ID int name string price float32 } func main(){ //structural morphology fmt.Println(Book{1,"java",32.5}) fmt.Println(Book{ID: 2,name: "c language",price: 40.5}) var book Book book.ID = 3 book.name = "Go language" book.price = 29.9 fmt.Println("ID:",book.ID,"name:",book.name,"price:",book.price) }
15, Slice
1. Slice
Slicing is an abstraction of an array. The length of the slice is not fixed, and elements can be added, which may increase the capacity of the slice.
Define slice:
Declare an array of unspecified size to define the slice. The slice does not need to specify the length
var Slice name []Variable type
Or use the make() function to create the slice. len is the length of the array and the initial length of the slice
var Slice name []Variable type = make([]Variable type,len)
It can also be abbreviated as:
Slice Name:= make([]Variable type,len)
You can also specify capacity, where capacity is an optional parameter
make([]T,len,capacity)
2. Initialization
(1) Directly initialize the slice, [] represents the slice type, {1,2,3} initialization initial values are 1, 2, 3, where cap=len=3
s :=[] int{1,2,3}
(2) Initialize slice s, which is a reference to array arr
s := arr[:]
(3) Create a new slice of the elements in the arr from the subscript startindex to endindex-1
s := arr[startindex:endindex]
(4) The default endindex will represent the last element up to arr
s := arr[startindex:]
(5) The default startindex will indicate starting from the first element of the arr
s := arr[:endindex]
(6) Initialize slice s1 with slice s
s1 := s[startindex:endindex]
(7) Initialize slice s with built-in function make()
s :=make([]int,len,cap)
3. len() and cap() functions
Slices are indexable, and the length can be obtained by the len() method
Slicing provides a method to calculate the capacity. cap() can measure the maximum length of slicing
4. Empty (nil) slice
A slice defaults to nil and its length is 0 before initialization
5. Set the cut slice by setting the lower and upper limits
For example:
numbers[1:4] //Slice from index 1 to index 4 (not included)
6. append() and copy() functions
If you want to increase the capacity of the slice, you must create a new and larger slice and copy the contents of the original slice
var nums []int //Define slice nums=append(nums,1) //Append element 1 to slice num nums=append(nums,2,3,4) //Append elements 2, 3, 4 to slice num nums1 :=make([]int,len(nums),(cap(nums))*2) //Create a new slice, copy(nums1,nums) //Copy nums slice to nums1
7. Instance
//section var s =make([]int,3,6) fmt.Printf("len=%d cap=%d slice=%v \n",len(s),cap(s),s) var num []int if(num == nil){ fmt.Println("The slice is empty") } numbers := []int{0,1,2,3,4,5,6,7,8,9} fmt.Println("numbers ==",numbers) fmt.Println("numbers[1:4] ==",numbers[1:4]) fmt.Println("numbers[:3] ==",numbers[:3]) fmt.Println("numbers[3:] ==",numbers[3:]) var nums []int fmt.Printf("len=%d cap=%d slice=%v \n",len(nums),cap(nums),nums) nums=append(nums,1) fmt.Printf("len=%d cap=%d slice=%v \n",len(nums),cap(nums),nums) nums=append(nums,2,3,4) fmt.Printf("len=%d cap=%d slice=%v \n",len(nums),cap(nums),nums) nums1 :=make([]int,len(nums),(cap(nums))*2) copy(nums1,nums) fmt.Printf("len=%d cap=%d slice=%v \n",len(nums1),cap(nums1),nums1)