golang slice index out of range错误

直接上代码

var group []string
    group[0]="abc"
    fmt.Println(group[0])

编译正常,运行报错如下

panic: runtime error: index out of range

goroutine 1 [running]:
panic(0x47a880, 0xc42000a110)
    /opt/tools/go1.7.3/src/runtime/panic.go:500 +0x1a1
main.main()
    /opt/IdeaProjects/test-embeded-struct/main.go:11 +0x14
exit status 2

index越界,于是改了一下代码

    var group []string
    fmt.Println(len(group))
    fmt.Println(cap(group))
    group[0]="abc"
    fmt.Println(group[0])

输出如下

0
0
panic: runtime error: index out of range

goroutine 1 [running]:
panic(0x48fec0, 0xc42000a110)
    /opt/tools/go1.7.3/src/runtime/panic.go:500 +0x1a1
main.main()
    /opt/IdeaProjects/test-embeded-struct/main.go:13 +0x10a
exit status 2

也就是说,slice声明的时候如果不同时初始化数据,默认长度和容量都是0,下标0意味着长度是1,所以index越界了。


那么,使用slice的时候有下面几种方式


第一,声明的时候初始化数据,例如

test:=[]string{"a","b","c"}

第二,从已经初始化数据的slice‘切’出来

test:=[]string{"a","b","c"}
your_string=test[0:1]

第三,append方法,会默认扩容,

var group []string
fmt.Println(len(group))
fmt.Println(cap(group))
group=append(group,"hahaha")
group[0]="abc"
fmt.Println(len(group))
fmt.Println(cap(group))
fmt.Println(group[0])

输出

0
0
1
1
abc

append方法在slice长度不足的时候,会进行扩容,注释如下

// The append built-in function appends elements to the end of a slice. If
// it has sufficient capacity, the destination is resliced to accommodate the
// new elements. If it does not, a new underlying array will be allocated.
// Append returns the updated slice. It is therefore necessary to store the
// result of append, often in the variable holding the slice itself:
//  slice = append(slice, elem1, elem2)
//  slice = append(slice, anotherSlice...)
// As a special case, it is legal to append a string to a byte slice, like this:
//  slice = append([]byte("hello "), "world"...)
func append(slice []Type, elems ...Type) []Type
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值