数组
数组的声明
var a [3]int//默认初始化为零值
a[0] = 2
b :=[3]int{1, 2 ,3 }
c :=[2][2]int{{1,2},{3,4}}
package array_test
import "testing"
func TestArrayInt(t *testing.T) {
var a [3]int
//b := [3]int{1,2,3}
//var b = [3]int{1,2,3}
//var b [3]int = [3]int{1,2,3}
//var b [3]int = [...]int{1,2,3}
b := [...]int{1,2,3}
t.Log(a[0],a[1])
t.Log(b[0],b[1])
}
func TestArrayTraval(t *testing.T) {
arr := [...]int{1,2,3,4,5}
for i := 0; i < len(arr); i++ {
t.Log(arr[i])
}
for idx,e := range arr {
t.Log(idx,e)
}
for _,e := range arr {
t.Log(e)
}
}
数组的截取
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[1:]//2,3,4,5
a[:3]1,2,3
func TestArraySection(t *testing.T) {
arr := [...]int{1,2,3,4,5}
arr_sec := arr[:3]
t.Log(arr_sec)
}
切片
切片内部结构
- 一个指针,指向一片连续内存空间(数组)
- len,数组元素个数
- cap,内部数组的容量
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[2])
s2 = append(s2,1)
t.Log(len(s2),cap(s2))
t.Log(s2[0],s2[1],s2[2],s2[3])
s := []int{}
t.Log(len(s),cap(s))
}
slice的增长
- cap翻倍增长
- slice的灵活是有代价的
切片共享存储空间
func TestSliceGrowing(t *testing.T) {
s := []int{}
for i := 0; i < 10; i++ {
s = append(s,i)
t.Log(len(s),cap(s))
}
}
func TestSliceShareMemory(t *testing.T) {
num := []int{1,2,3,4,5,6,7,8,9,10}
t2 := num[3:6]
t.Log(t2,len(t2),cap(t2))
t3 := num[5:8]
t3[0] = 0
t.Log(t3,len(t3),cap(t3))
t.Log(t2,len(t2),cap(t2))
}
数组vs切片
1.容量是否可伸缩
- 是否可以进行比较
func TestSliceComparing(t *testing.T) {
a := []int{1,2,3}
b := []int{1,2,3}
if a == b {
t.Log("equal")
}
}
slice can only be compared to nil
网友评论