golang slice index out of range错误
来源:互联网 发布:淘宝主图背景图片大全 编辑:程序博客网 时间:2024/06/06 20:11
直接上代码
var group []string group[0]="abc" fmt.Println(group[0])
编译正常,运行报错如下
panic: runtime error: index out of rangegoroutine 1 [running]:panic(0x47a880, 0xc42000a110) /opt/tools/go1.7.3/src/runtime/panic.go:500 +0x1a1main.main() /opt/IdeaProjects/test-embeded-struct/main.go:11 +0x14exit status 2
index越界,于是改了一下代码
var group []string fmt.Println(len(group)) fmt.Println(cap(group)) group[0]="abc" fmt.Println(group[0])
输出如下
00panic: runtime error: index out of rangegoroutine 1 [running]:panic(0x48fec0, 0xc42000a110) /opt/tools/go1.7.3/src/runtime/panic.go:500 +0x1a1main.main() /opt/IdeaProjects/test-embeded-struct/main.go:13 +0x10aexit 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 []stringfmt.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])
输出
0011abc
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 0
- golang slice index out of range错误
- goLang panic: runtime error: slice bounds out of range
- Parameter index out of range 错误
- 错误:list assignment index out of range 和list index out of range
- python PIL, 错误:IndexError: string index out of range
- IndexError: list index out of range的错误原因
- **Python错误记录:IndexError: list index out of range**
- 解决SSO客户端验证错误String index out of range
- list index out of range
- RangeError: index out of range
- list index out of range
- tuple index out of range
- String index out of range: -1
- IndexError: list index out of range
- Range or index out of bounds
- Mybatis 错误信息:Parameter index out of range
- String index out of range: -1
- Java String index out of range: -1
- 【WebDriver】调用JavaScript
- WordPress增加侧边栏sidebar
- lavarel5.2中非法登录
- Caffe中Loss Layer原理的简单梳理
- MongoDB基础操作
- golang slice index out of range错误
- 历届试题 错误票据
- csdn如何转载别人的文章
- 46. Permutations(unsolved)
- wordpress修改固定链接之后 无法访问的解决办法 标签: WordPress 2015-09-24 14:09 223人阅读 评论(0) 收藏 举报 分类: WordPress(6) 本地同
- java日志组件介绍(common-logging,log4j,slf4j,logback )
- js callback , ajax call back can observer mvvm
- C++智能指针
- zookeeper学习之路一