使用append向slice追加元素遇到的坑,在此总结一下。
一,细节1
urls := make(map[string]string, 3)
urls["baidu"] = "www.baidu.com"
urls["google"] = "www.google.com"
urls["csdn"] = "www.csdn.net"
names := make([]string, len(urls))
for key, _ := range urls {
names = append(names, key)
}
fmt.Println(names,len(names))
输出结果
[ csdn baidu google] 6
前面多了几个空格,长度为6,与预期的结果不一致
修改代码
names := make([]string, 0)
for key, _ := range urls {
names = append(names, key)
}
fmt.Println(names,len(names))
或者
var names []string
for key, _ := range urls {
names = append(names, key)
}
fmt.Println(names,len(names))
输出结果
[baidu google csdn] 3
总结:append无论如何都是从slice的尾部开始追加数据,原来的slice只有3个长度,现在每一次append都要重新分配一次内存
二、细节2
s1 := []int{1, 2, 3}
s2 := []int{4, 5}
s1 = append(s1, s2)
fmt.Println(s1)
程序报错:cannot use s2 (type []int) as type int in append
修改为:
s1 := []int{1, 2, 3}
s2 := []int{4, 5}
s1 = append(s1, s2...)
fmt.Println(s1)
输出结果:
[1 2 3 4 5]
总结:append切片时候别漏了'...'
三、细节3
p := new([]int) //p == nil; with len and cap 0
fmt.Println(p)
v := make([]int, 10, 50) // v is initialed with len 10, cap 50
fmt.Println(v)
输出结果:
&[]
[0 0 0 0 0 0 0 0 0 0]
有疑问加站长微信联系(非本文作者)