go 语言 first argument to append must be slice
生活随笔
收集整理的這篇文章主要介紹了
go 语言 first argument to append must be slice
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
錯誤代碼
func TestSliceGrowing(t *testing.T) {s := [4]int{1, 2, 3, 4}for i :=0; i<10; i++ {s = append(s, i)t.Log(len(s), cap(s))} }報錯代碼
s = append(s, i)原因:append的第一個參數必須是切片
更正
func TestSliceGrowing(t *testing.T) {s := []int{1, 2, 3, 4}for i :=0; i<10; i++ {s = append(s, i)t.Log(len(s), cap(s))} }cap 的值在初始化的時候,如果切片沒有初始值,則為1,如果有初始值,如上,則為元素個數len,在執行append后,如果len超過cap,則cap值變為原來的兩倍。
func TestSliceCap(t *testing.T) {arr := [5]int{1, 2, 3, 4, 5}s := arr[:2]t.Log(len(s), cap(s)) }len :2, cap 5
cap = arr length - start index
我的公眾號
創作挑戰賽新人創作獎勵來咯,堅持創作打卡瓜分現金大獎總結
以上是生活随笔為你收集整理的go 语言 first argument to append must be slice的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 7位qq号多少钱啊?
- 下一篇: C++并发编程实战(豆瓣评分5.4)