【go学习笔记】六、数组和切片
数组的声明
var a [3]int // 声明并初始化为默认零值
a[0] = 1
b := [3]int{1,2,3} //声明同时初始化
c := [2][2]int{{1,2},{3,4}} //多维数组初始化
数组元素遍历
func TestArrayTravel(t *testing.T) {
arr3 := [...]int{1, 3, 4, 5}
for i := 0; i < len(arr3); i++ {
t.Log(arr3[i])
}
for idx, e := range arr3 {
t.Log(idx, e)
}
}
输出
=== RUN TestArrayTravel
--- PASS: TestArrayTravel (0.00s)
array_test.go:17: 1
array_test.go:17: 3
array_test.go:17: 4
array_test.go:17: 5
array_test.go:21: 0 1
array_test.go:21: 1 3
array_test.go:21: 2 4
array_test.go:21: 3 5
PASS
Process finished with exit code 0
数组截取
a[开始索引(包含),结束索引(不包含)]
a := [...]int{1, 2, 3, 4, 5}
a[1:2] // 2
a[1:3] // 2,3
a[1:len(a)] // 2,3,4,5
a[:3] // 1,2,3
示例代码
func TestArraySection(t *testing.T) {
arr3 := [...]int{1, 2, 3, 4, 5}
arr_sec :=arr3[3:]
t.Log(arr_sec)
}
输出
=== RUN TestArraySection
--- PASS: TestArraySection (0.00s)
array_test.go:28: [4 5]
PASS
Process finished with exit code 0
切片内部结构
- 切片是一个结构体
- 第一个参数是指针,指向一个数组(连续存储空间)
- 元素个数
- 容量
package slice_test
import "testing"
func TestSliceInit(t *testing.T) {
var s0 []int
t.Log(len(s0), cap(s0))
s0 = append(s0, 1)
t.Log(len(s0), cap(s0))
s1 := []int{1, 2, 3, 4}
t.Log(len(s1), cap(s1))
s2 := make([]int, 3, 5)
t.Log(len(s2), cap(s2))
//t.Log(s2[0], s2[1], s2[3], s2[4])
//panic: runtime error: index out of range [recovered]
//panic: runtime error: index out of range
t.Log(s2[0], s2[1], s2[2])
s2 = append(s2, 1)
t.Log(s2[0], s2[1], s2[2], s2[3])
t.Log(len(s2), cap(s2))
}
输出
=== RUN TestSliceInit
--- PASS: TestSliceInit (0.00s)
slice_test.go:7: 0 0
slice_test.go:9: 1 1
slice_test.go:12: 4 4
slice_test.go:15: 3 5
slice_test.go:20: 0 0 0
slice_test.go:23: 0 0 0 1
slice_test.go:24: 4 5
PASS
Process finished with exit code 0
切片共享存储结构
func TestSliceShareMemory(t *testing.T) {
year := []string{"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct","Nov", "Dec"}
Q2 := year[3:6]
t.Log(Q2, len(Q2), cap(Q2))
summer := year[5:8]
t.Log(summer, len(summer), cap(summer))
summer[0] = "Unknow"
t.Log(Q2)
t.Log(year)
}
输出
=== RUN TestSliceShareMemory
--- PASS: TestSliceShareMemory (0.00s)
slice_test.go:39: [Apr May Jun] 3 9
slice_test.go:42: [Jun Jul Aug] 3 7
slice_test.go:44: [Apr May Unknow]
slice_test.go:45: [Jan Feb Mar Apr May Unknow Jul Aug Sep Oct Nov Dec]
PASS
Process finished with exit code 0
数组vs. 切片
- 容量是否可伸缩
- 是否可以进行比较
func TestSliceCompare(t *testing.T) {
a := []int{1, 2, 3, 4}
b := []int{1, 2, 3, 4}
if a == b {
t.Log("equal")
}
}
输出
# command-line-arguments_test [command-line-arguments.test]
./slice_test.go:51:7: invalid operation: a == b (slice can only be compared to nil)
Compilation finished with exit code 2
slice can only be compared to nil