Go language basics three
Definition of slices
1. Slice: A slice is a reference to an array, so a slice is a reference type. But itself is a structure, and the value copy is passed.
2. The length of the slice can be changed, so the slice is a variable array.
3. The slice traversal method is the same as that of an array. You can use len() to find the length. Indicates the number of available elements, read and write operations cannot exceed this limit.
4. Cap can find the maximum expansion capacity of slice, which cannot exceed the array limit. 0 <= len(slice) <= len(array), where array is an array referenced by slice.
5. Definition of slice: var variable name [] type, such as var str []string var arr []int.
6. If slice == nil, then the results of len and cap are equal to 0.
How to create slices
package main import "fmt" func main() { var s1 []int if s1 == nil { ("It's empty") } else { ("Not empty") } s2 := []int{} var s3 []int = make([]int, 0) (s1, s2, s3) var s4 []int = make([]int, 0, 0) (s4) s5 := []int{1, 2, 3} (s5) arr := [5]int{1, 2, 3, 4, 5} var s6 []int s6 = arr[1:4] (s6) }
We first define aAn array of variables with name s1 and data type int is not initialized, and use it at the same timeifMake a judgment, from the demo of this question, the answer isnull;Nexts1、s2、s3These three arrays are printed out becauseNone of the three arrays are initialized, so the values printed by the three arrays are all[]
;s4ArrayNo initialization operation was performed either, so the printout of s4 array is also[]
; As the name suggests, 45 is printed out[1,2,3]
;We initialize the s6 array and usearr arrayThe elements ofHow to use slices, slice s6, and the final print result is[2,3,4]
Slice initialization
package main import ( "fmt" ) var arr = [...]int{0, 1, 2, 3, 4, 5, 6, 7, 8, 9} var slice0 []int = arr[2:8] var slice1 []int = arr[0:6] //It can be abbreviated as var slice []int = arr[:end]var slice2 []int = arr[5:10] //It can be abbreviated as var slice[]int = arr[start:]var slice3 []int = arr[0:len(arr)] //var slice []int = arr[:] var slice4 = arr[:len(arr)-1] //Remove the last element of the slicefunc main() { ("Global variable: arr %v\n", arr) ("Global variable: slice0 %v\n", slice0) ("Global variable: slice1 %v\n", slice1) ("Global variable: slice2 %v\n", slice2) ("Global variable: slice3 %v\n", slice3) ("Global variable: slice4 %v\n", slice4) ("-----------------------------------\n") arr2 := [...]int{9, 8, 7, 6, 5, 4, 3, 2, 1, 0} slice5 := arr[2:8] slice6 := arr[0:6] //It can be abbreviated as slice := arr[:end] slice7 := arr[5:10] //It can be abbreviated as slice := arr[start:] slice8 := arr[0:len(arr)] //slice := arr[:] slice9 := arr[:len(arr)-1] //Remove the last element of the slice ("Local variable: arr2 %v\n", arr2) ("Local variable: slice5 %v\n", slice5) ("Local variable: slice6 %v\n", slice6) ("Local variable: slice7 %v\n", slice7) ("Local variable: slice8 %v\n", slice8) ("Local variable: slice9 %v\n", slice9) }
First, we follow the code requirementsDefine four arrays, all of which are of type intand slice them separately. We're dealing with itslice4 arrayWhen it comes toRemove the last element of the slice
The above calculation results are obvious. The author will not explain them here. If there is any problem, you can read the explanation of the article in the array in detail.
package main import ( "fmt" ) var slice0 []int = make([]int, 10) var slice1 = make([]int, 10) var slice2 = make([]int, 10, 10) func main() { ("make global slice0:%v\n", slice0) ("make global slice1:%v\n", slice1) ("make global slice2:%v\n", slice2) ("--------------------------------------") slice3 := make([]int, 10) slice4 := make([]int, 10) slice5 := make([]int, 10, 10) ("make local slice3:%v\n", slice3) ("make local slice4:%v\n", slice4) ("make local slice5:%v\n", slice5) }
Due to the above global and local variablesNo initialization operation is performed,thereforeAll values of the array are 0
package main import ( "fmt" ) func main() { data := [...]int{0, 1, 2, 3, 4, 5} s := data[2:4] s[0] += 100 s[1] += 200 (s) (data) }
existmainIn the function, we define aAn array named data, with arbitrary length and an int type,andPerform initialization assignment operation; Use variable s to slice array data, while maintainingBefore and afterThe syntax rules of the slice element should be{2,3}
, In the next step of assignment operation, we will perform the assignment operation 2 (Index is 0), the result is 102; similarly,s[1]
The resulting value is 203. Then everyone knows the last printout, so I won't go into details.
package main import "fmt" func main() { s1 := []int{0, 1, 2, 3, 8: 100} // By initializing the expression construction, you can use the index number. (s1, len(s1), cap(s1)) s2 := make([]int, 6, 8) // Create with make, specify len and cap values. (s2, len(s2), cap(s2)) s3 := make([]int, 6) // Omit cap, which is equivalent to cap = len. (s3, len(s3), cap(s3)) }
From the above code, we have defined aArray named s1, array length is 9, data type is int type. When we call the function to print it out, becauseThe 9th element in the array is replaced with 100, so the final result is[0 1 2 3 0 0 0 0 100] 9 9
, the last two arrays are the same; it is worth mentioning that if we omit cap,Default is cap = len
package main import "fmt" func main() { s := []int{0, 1, 2, 3} p := &s[2] // *int, get the underlying array element pointer. *p += 100 (s) }
We define an array that stores 4 elements, and then weUse & to get the underlying array element pointer,ThenMake it with +100 operation, the final element with index 3 is assigned a value of 102, so the final result is[0 1 102 3]
package main import ( "fmt" ) func main() { d := [5]struct { x int }{} s := d[:] d[1].x = 10 s[2].x = 20 (d) ("%p, %p\n", &d, &d[0]) }
We're inmainIn the methodDefine a function body structure, defines a function bodyvariable of type int, named x, then we copy the array d into s, and at the same timeAssign the element indexed to 1 in the d array to 10; Similarly,Elements with index 2 are assigned a value of 20, so the print result is[{0} {10} {20} {0} {0}]
, I won't repeat the printing of the address value immediately
This is the article about this article that will introduce you to the secrets of slicing in Go. For more relevant Go slicing content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!