What is an array?
Array
An array is a sequence of particular type elements composed of a fixed length, it may be composed of an array of zero or more elements
Array method definition?
method one
package main
import "fmt"
func arraytest() {
var x [3] int
fmt.Println(x)
}
// 输出 [0 0 0]
func main() {
arraytest()
}
Use Quick declare an array
x3 :=[3] int {112,78}
fmt.Println(x3)
输出 [112 78 0]
// get an array of values
var x2[3] int
x2[0] = 1 //第一个元素
x2[1] = 11
x2[2] = 22
fmt.Println(x2)
输出 [1 11 22]
// use a for loop to get the array of data
x6 :=[...] int {3,5,6,82,34}
for i :=0; i< len(x6);i++{
fmt.Println(i,x6[i])
}
// 输出 如下 0 表示索引号, 3表示 对应的具体值
0 3
1 5
2 6
3 82
4 34
Providing use range of language // go get in the way
for i,v := range x6{
fmt.Printf("%d of x6 is %d\n",i,v)
}
// 输出
0 3
1 5
2 6
3 82
4 34
// only access elements
for _,v1 :=range x6 {
fmt.Printf("x6 array value is %d\n",v1)
}
// 输出
0 of x6 is 3
1 of x6 is 5
2 of x6 is 6
3 of x6 is 82
4 of x6 is 34
slice
What is the slice (slice)?
Slice (Slice) is Golang the kind of special data structure, this data structure easier to use and manage data sets
// define slices
package main
import "fmt"
func slicetest() {
a1 :=[4] int {1,3,7,22}
fmt.Println(a1)
// 输出
[1 3 7 22]
var b1 []int = a1[1:4]
fmt.Println(b1,len(b1))
// 输出
[3 7 22] 3
}
func main() {
slicetest()
}
// make a statement using sections
make initialization function slice of time, if not indicate its capacity, he would be the same length and, if indicated its capacity during initialization
s1 :=make([]int, 5)
fmt.Printf("The length of s1: %d\n",len(s1)) # 长度
fmt.Printf("The capacity of; s1: %d\n",cap(s1)) # cap 容量
fmt.Printf("The value of s1:%d\n",s1)
// 输出
The length of s1: 5
The capacity of; s1: 5
The value of s1:[0 0 0 0 0]
s12 :=make([]int, 5,8) # 指明长度为 5, 容量为8
fmt.Printf("The length of s12: %d\n",len(s12))
fmt.Printf("The capacity of; s12: %d\n",cap(s12))
fmt.Printf("The value of s12:%d\n",s12)
// 输出
The length of s12: 5
The capacity of; s12: 8
The value of s12:[0 0 0 0 0]
//
s3 := []int{1, 2, 3, 4, 5, 6, 7, 8}
s4 := s3[3:6]
fmt.Printf("The length of s4: %d\n", len(s4))
fmt.Printf("The capacity of s4: %d\n", cap(s4))
fmt.Printf("The value of s4: %d\n", s4)
// 输出
The length of s4: 3 # 长度为3
The capacity of s4: 5 # 容量为5
The value of s4: [4 5 6]
// 切片与数组的关系
切片的容量可以看成是底层数组元素的个数
s4 是通过s3 切片获得来的,所以s3 的底层数组就是s4 的底层数组,切片是无法向左拓展的,所以s4 无法看到s3 最左边的三个元素,所以s4 的容量为5
// get sliced
before_slice :=[] int {1,4,5,23,13,313,63,23}
after_slice := before_slice[3:7]
fmt.Println("array before change",before_slice)
// 使用for range 遍历
for i := range after_slice{
after_slice[i]++
}
fmt.Println("after cahnge",before_slice)
// output
array before change [1 4 5 23 13 313 63 23]
after cahnge [1 4 5 24 14 314 64 23]
The difference between arrays and slices
Whether capacity scalable? Array capacity can not stretch, slice can
It can be compared? // array of the same length may be compared