当前位置:网站首页>go语言切片Slice和数组Array对比panic: runtime error: index out of range问题解决
go语言切片Slice和数组Array对比panic: runtime error: index out of range问题解决
2022-06-27 19:50:00 【大锤爱编程】
初学Go 语言的数组(array)类型和切片(slice)类型,我对这两个概念犯迷糊,一时不知道怎么用?到底什么时候用数组还是什么时候用切片
前言
在go语言的学习历程当中,slice数据类型引起了我的好奇心。为啥不直接使用Slice,是人性的扭曲还是道德的沦丧~,下面让我们一探究竟~~
一、go slice是什么
go语言中的slice是一个基于Array封装的数据结构,go语言中slice的使用频率远高于array,其身影频频出现在源码实现当中。slice相对于Array的优点就是其可以动态调整自己的size,不像Array的Size是固定的。
二、go slice实战案例
1.slice创建、使用
slice的创建有两个方法分别是使用字面量定义和使用make函数。除过slice创建,其他slice的生成办法均是从现有slice分片或者array上做slice分片操作。
slice创建代码:
package main
import (
"fmt"
"reflect"
)
func main() {
//字面创造Slice
sliceOne := []string{"a", "b"}
//使用make函数创造slice
sliceTwo := make([]string, 10)
sliceThree := make([]int, 10)
fmt.Printf("使用字面量创建的slice%s\n",reflect.ValueOf(sliceOne).String())
fmt.Printf("使用make函数创建的slice:%s\n",reflect.ValueOf(sliceTwo).String())
fmt.Printf("使用make函数创建的slice:%s\n",reflect.ValueOf(sliceThree).String())
}
使用字面量创建的slice<[]string Value>
使用make函数创建的slice:<[]string Value>
使用make函数创建的slice:<[]int Value>
Process finished with the exit code 02、slice的长度和容量概念理解
学习过程中,很多小伙伴会对slice的长度和容量问题有着很多混淆。
这个地方可以把切片比喻成一个可以装10个苹果的袋子,现在的袋子里面有三颗苹果。切片的长度就是袋子已经装的果子的个数,目前是3个。切片的容量就是这个袋子一共能装多少个果子,对于这个袋子来说就是10。那么把代码替换成切片,把苹果替换成元素,是不是就懂了撒~
下面就是该问题的处理办法就是直接去官方,看源码。看看第一手资料怎么讲!

长度:slice中拥有的元素个数,如果slice是nil的话,则元素个数长度是0 英文:the number of elements in v; if v is nil, len(v) is zero
容量:slice切片的长度能够到达的最大值 英文:Slice: the maximum length the slice can reach when resliced;
代码验证环节:
package main
import (
"fmt"
)
func main() {
sliceOne := []string{"a", "b"}
strings := sliceOne[0:1]
fmt.Printf("切片的长度:%d\n",len(strings))
fmt.Printf("切片的容量:%d\n",cap(strings))
}
代码结果输出:
切片的长度:1
切片的容量:2代码原理解析:
strings由sliceOne切片而来,切出来的片上数据有的是0到1,有一个元素,故其对应的长度是1。
因为切片是一个引用类型,只在原始切片上切出了0到1的位置,剩余的空位还有1,故其容量等于长度加剩余元素位置数。
3. 切片扩容及slice panic: runtime error: index out of range
slice越界代码实例如下:
sliceOne := []string{"a", "b"}
//使用make函数创造slice
s := sliceOne[2]
fmt.Printf(s)使用sliceOne[2]语句时,数组越界报错。
实际开发过程中,总会有slice容量不够用的时候,该怎么扩容,如何保证安全扩容?
go语言官方提供的扩容办法就是创建一个新的更大的分片,将老分片的数据内容迁移到新的切片当中。
代码展示:
package main
import (
"fmt"
)
func main() {
sliceOne := []string{"a", "b"}
fmt.Printf("切片扩容前")
fmt.Printf("切片的长度:%d\n",len(sliceOne))
fmt.Printf("切片的容量:%d\n",cap(sliceOne))
t := make([]string, len(sliceOne), (cap(sliceOne))*2)
copy(t, sliceOne)
sliceOne = t
fmt.Printf("切片扩容后")
fmt.Printf("切片的长度:%d\n",len(sliceOne))
fmt.Printf("切片的容量:%d\n",cap(sliceOne))
}结果展示:
切片的长度:2
切片的容量:2
切片的长度:2
切片的容量:4
从代码结果上看出新切片的长度是2,容量是4,也再次验证了切片的长度取决于存放了多少元素,切片的容量取决于已存放的元素数量加剩余位置数。
总结
go语言中slice的应用和使用相对来说方便快捷很多,不过也有一些小小的暗坑等待大家发现和整理哦~后续我会在我的博客中,继续发布有关于go语言使用的tips和技巧~
欢迎关注点赞、收藏、评论~~

边栏推荐
- [LeetCode]515. Find the maximum value in each tree row
- 使用Fiddler模拟弱网测试(2G/3G)
- [LeetCode]100. Same tree
- regular expression
- C语言程序设计详细版 (学习笔记1) 看完不懂,我也没办法。
- [LeetCode]508. 出现次数最多的子树元素和
- 扁平数组和JSON树的转换
- 关于davwa的SQL注入时报错:Illegal mix of collations for operation ‘UNION‘原因剖析与验证
- Record a list object traversal and determine the size of the float type
- Use Fiddler to simulate weak network test (2g/3g)
猜你喜欢

Deep learning has a new pit! The University of Sydney proposed a new cross modal task, using text to guide image matting

Experience sharing of meituan 20K Software Test Engineers

Secret script of test case design without leakage -- module test

渗透学习-sql注入过程中遇到的问题-针对sort=left(version(),1)的解释-对order by后接字符串的理解

VMware virtual machine PE startup

GBase 8a的create database 会被查询耗时很长怀疑卡住的现象分析

不外泄的测试用例设计秘籍--模块测试

crontab定时任务常用命令
![[MySQL] database function clearance Tutorial Part 2 (window function topic)](/img/03/2b37e63d0d482d5020b7421ac974cb.jpg)
[MySQL] database function clearance Tutorial Part 2 (window function topic)
![The problem of minimum modification cost in two-dimensional array [conversion question + shortest path] (dijkstra+01bfs)](/img/e6/4eb2ddf4d9bac5e40bf2e96656d294.png)
The problem of minimum modification cost in two-dimensional array [conversion question + shortest path] (dijkstra+01bfs)
随机推荐
Beijing University of Posts and Telecommunications - multi-agent deep reinforcement learning for cost and delay sensitive virtual network function placement and routing
Codeforces Round #721 (Div. 2)
Gbase 8A OLAP analysis function cume_ Example of dist
MONTHS_BETWEEN函数使用
Sharing | intelligent environmental protection - ecological civilization informatization solution (PDF attached)
Selenium上传文件有多少种方式?不信你有我全!
[LeetCode]515. Find the maximum value in each tree row
qt 大文件生成md5校验码
QT large file generation MD5 check code
Software test automation test -- interface test from entry to proficiency, learn a little every day
gomock mockgen : unknown embedded interface
Management system itclub (Part 1)
I think I should start writing my own blog.
Ellipsis after SQLite3 statement Solutions for
【mysql实战】查询语句实战演示
Crontab scheduled task common commands
Summary of Web testing and app testing by bat testing experts
[LeetCode]508. 出現次數最多的子樹元素和
Yarn performance tuning of CDH cluster
[LeetCode]30. 串联所有单词的子串
