This is the 12th chapter of Golang Language Learning Tutorial
The previous section learned the knowledge of the Golang array, and this section began to learn the concept application of slices; first, multidimensional arrays
Multidimensional arrays
The go language can create multidimensional arrays:
package mainimport "fmt"func test(a [3][2]string) { //定义函数test,输入值为多维二维数组 a for _, v1 := range a { for _, v2 :=range v1 { fmt.Printf("%s ", v2) //两次循环得到其中一个值并输出 } fmt.Println("\n") }}func main() { a := [3][2]string{ //定义一个二维数组 {"1x1", "1x2"}, {"2x1", "2x2"}, {"3x1", "3x2"}, } test(a) //调用函数输出}
The above program uses a shorthand syntax to declare a two-dimensional array a , using two range loops to print the values of the array.
The output of the above program is:
1x1 1x2
2x1 2x2
3x1 3x2
Another declaration syntax is to add a string index one at a to achieve the purpose of initializing a two-dimensional array:
func main() { var b [3][2]string b[0][0] = "apple" b[0][1] = "samsung" b[1][0] = "microsoft" b[1][1] = "google" b[2][0] = "AT&T" b[2][1] = "T-Mobile" fmt.Printf("\n") test(b)}
Slice
Slices are a convenient, flexible, and powerful package built from arrays. The slice itself does not have any data, just a reference to an existing array.
Slices with elements of type T are represented by []T , T represents the type of elements in slice:
package mainimport "fmt"func main(){ a := [6]int{45, 56, 67, 78, 89, 90} var b []int = a[1:5] //创建一个切片 从 a[1] - a[4] fmt.Println(b)}
In the above program, a[start:end] a a slice from an array index start is created end-1 .
a[1:5]Created a slice from a[1] - a[4] . The value of Slice B is:[56 67 78 89]
There is another way to create a slice:
package mainimport "fmt"func main(){ c := []int{6, 7, 8} //创建一个数组 c ,并返回一个存储在 c 中的切片引用 fmt.Println(c)}
Modify slices
A slice does not have its own data, it is just a representation of the underlying array. Therefore, any modifications to the slices are reflected in the underlying array.
package mainimport "fmt"func main(){ num := [...]int{1, 2, 3, 4, 5, 6, 7, 8, 9} //定义数组 num snum := num[2:8] //创建切片从 num[2] - num[7] fmt.Println("before change", num) //输出改变前 for i := range snum { snum[i]++ //给切片每个参数+1 } fmt.Println("after change", num) //输出改变后}
A slice is created in the above program, and the For loop increments the index of the slice one at a time, and snum when the array is printed, you can see that changes to the slice are reflected in the array:
Before change [1 2 3 4 5 6 7 8 9]
After change [1 2 4 5 6 7 8 9 9]
And when multiple slices share the same array, the changes that are made to each slice are reflected in the array.
When defining a slice, if the start and end values are not indicated, such as: the num[:] default values for start and end are 0 , respectively, references to the len (numa) entire array.
Length and capacity of slices
The length of the slice corresponds to the number of elements in the slice, and the length cannot exceed capacity. The capacity is typically from the beginning of the slice to the end of the underlying array.
Write a month program to understand the length and capacity of the slice:
package mainimport "fmt"func main(){ /*一个数组的第一个索引是从0开始,若想跳过0,则用1:的方式,第0个元素会自动初始化为空字符串*/ months := [...]string{1: "Jan", 2: "Feb", 3: "Mar", 4: "Apr", 5: "May", 6: "Jun", 7: "Jul", 8: "Aug", 9: "Sep", 10: "Oct", 11: "Nov", 12: "Dec"} Q2 := months[4:7] //第二季度 summer := months[6:9] //夏天 fmt.Printf("length of Q2 is %d, capacity is %d\n", len(Q2), cap(Q2)) fmt.Printf("length of summer is %d, capacity is %d", len(summer), cap(summer))}
In the above program, the slice is created by the index of the Q2 array months 4 , so the length of the 6 Q2 is, because the 3 slice is created from the months index of the array 4 , so the capacity of the Q2 is 从4到12 : 9; slice Sunmer the same.
The result of the above program operation is:
Length of Q2 is 3, capacity is 9
Length of Summer is 3, capacity is 7
If the slice operation exceeds the capacity cap (s) upper limit will be error, but exceeding the length Len (s) upper limit means that the slice is expanded because the new tile length becomes larger.
fmt.Println(summer[:20]) //报错panic:runtime error: slice bounds out of range
package mainimport "fmt"func main(){ /*一个数组的第一个索引是从0开始,若想跳过0,则用1:的方式,第0个元素会自动初始化为空字符串*/ months := [...]string{1: "Jan", 2: "Feb", 3: "Mar", 4: "Apr", 5: "May", 6: "Jun", 7: "Jul", 8: "Aug", 9: "Sep", 10: "Oct", 11: "Nov", 12: "Dec"} Q2 := months[4:7] //第二季度 summer := months[6:9] //夏天 //fmt.Printf("length of Q2 %d, capacity %d\n", len(Q2), cap(Q2)) //fmt.Printf("length of summer %d, capacity %d", len(summer), cap(summer)) //fmt.Println(summer[:20]) //报错panic:runtime error: slice bounds out of range endlessSummer := summer[:5] //扩展summer长度,并给切片endlessSummer fmt.Println(endlessSummer) fmt.Printf("the length os endlessSummer is %d, capacity is %d", len(endlessSummer), cap(endlessSummer))}
The above program, extending the summer length, and assigning toendlessSummer
The result of the above program operation is:
The length OS Endlesssummer is 5, capacity is 7
Create slices with make
func make([]T,len,cap)[]t creates slices by passing type, length, and capacity.] The capacity is an optional parameter, and the default value is the slice length. The Make function creates an array and returns a slice that references the array.
package mainimport ( "fmt")func main() { i := make([]int, 5, 5) //引用make函数创建切片 fmt.Println(i)}
Append slice Element
The length of the array is fixed and cannot be increased, but the length of the slice can be increased, and the append new element can be added to the slice using the. The definition of the APPEND function is func append(s[]T,x ... T)[]T .
x ... T in a function definition means that the number of parameters x that the function accepts is variable. These types of functions are called mutable functions.
package mainimport "fmt"func main(){ cars := []string{"Ferrari", "Honda", "Ford"} //定义切片cars fmt.Println(cars) fmt.Println("old cars length is ", len(cars), "and capacity is ", cap(cars)) //输出cars的长度和容量 newcars := append(cars, "BYD") //cars 切片增加新元素并定义给另一个切片newcars fmt.Println(newcars) fmt.Println("new cars length is ", len(newcars), "and capacity is ", cap(newcars)) //输出newcars长度和容量}
In the above program, the original cars slice length is 3, the capacity is 3, we use the append function to add a new element, and assign to another slice newcars .
The result of the above program operation is:
[Ferrari Honda Ford]
Old cars length was 3 and capacity is 3
[Ferrari Honda Ford BYD]
New cars length is 4 and capacity is 6
Multidimensional slices
Like an array, a slice can have more than one dimension.
package mainimport "fmt"func main(){ /*多维数组*/ pls := [][]string { {"C", "C++"}, {"JavaScript"}, {"Go", "Rust"}, } for _, v1 := range pls { for _, v2 := range v1 { fmt.Printf("%s ", v2) } fmt.Printf("\n") }}
The result of the above program operation is:
C C + +
Javascript
Go Rust
The above is the study Golang slice article