当前位置:网站首页>Go language slice vs array panic: runtime error: index out of range problem solving
Go language slice vs array panic: runtime error: index out of range problem solving
2022-06-27 22:26:00 【Sledgehammer love programming】
Beginners Go An array of languages (array) Type and slice (slice) type , I am confused about these two concepts , I don't know how to use it ? When to use array or slice
Catalog
2、slice Understand the concept of length and capacity
3. Slice expansion and slice panic: runtime error: index out of range

Preface
stay go In the course of language learning ,slice The data type aroused my curiosity . Why not just use it Slice, Is the distortion of human nature or moral collapse ~, Let's take a look at ~~
One 、go slice What is it?
go In language slice It's based on Array Encapsulated data structure ,go In language slice The frequency of use is much higher than array, Its figure frequently appears in the source code implementation .slice be relative to Array Its advantage is that it can dynamically adjust its own size, Unlike Array Of Size Is constant .
Two 、go slice Practical cases
1.slice establish 、 Use
slice There are two ways to create a. S. are using literal definitions and using make function . Excepting slice establish , other slice The generation methods of are all from the existing slice Slice or array Do on slice Shard operation .
slice Create code :
package main
import (
"fmt"
"reflect"
)
func main() {
// Literal creation Slice
sliceOne := []string{"a", "b"}
// Use make Function creation slice
sliceTwo := make([]string, 10)
sliceThree := make([]int, 10)
fmt.Printf(" Created with literal slice%s\n",reflect.ValueOf(sliceOne).String())
fmt.Printf(" Use make Function created slice:%s\n",reflect.ValueOf(sliceTwo).String())
fmt.Printf(" Use make Function created slice:%s\n",reflect.ValueOf(sliceThree).String())
}
Created with literal slice<[]string Value>
Use make Function created slice:<[]string Value>
Use make Function created slice:<[]int Value>
Process finished with the exit code 02、slice Understand the concept of length and capacity
Learning process , A lot of kids will be right slice There is a lot of confusion about the length and capacity of .
This place can be compared to a place that can hold 10 An apple bag , There are three apples in the bag now . The length of the slice is the number of fruits in the bag , At present, it is 3 individual . The capacity of slicing is the total number of fruits in this bag , For this bag, it is 10. Then replace the code with slices , Replace the apple with the element , Is it right that I understand the meaning of Sa ~
The following is how to deal with this problem, which is to go directly to the official , Look at the source code . Look at the first-hand information !

length :slice Number of elements in , If slice yes nil Words , Then the length of the number of elements is 0 english :the number of elements in v; if v is nil, len(v) is zero
Capacity :slice The maximum length of the slice that can be reached english :Slice: the maximum length the slice can reach when resliced;
Code verification :
package main
import (
"fmt"
)
func main() {
sliceOne := []string{"a", "b"}
strings := sliceOne[0:1]
fmt.Printf(" The length of the slice :%d\n",len(strings))
fmt.Printf(" The volume of the slice :%d\n",cap(strings))
}
Code result output :
The length of the slice :1
The volume of the slice :2Code principle analysis :
strings from sliceOne Sliced , There are a lot of on-chip data cut out 0 To 1, There's an element , So the corresponding length is 1.
Because slice is a reference type , Only on the original slice 0 To 1 The location of , There are still... Vacant seats left 1, Therefore, its capacity is equal to the length plus the number of remaining element positions .
3. Slice expansion and slice panic: runtime error: index out of range
slice Examples of out of bounds code are as follows :
sliceOne := []string{"a", "b"}
// Use make Function creation slice
s := sliceOne[2]
fmt.Printf(s)Use sliceOne[2] When the sentence is , Array out of bounds error .
In the actual development process , There will always be slice When the capacity is not enough , How to expand the capacity , How to ensure safe expansion ?
go The expansion method provided by the language official is to create a new and larger partition , Migrate the data content of the old slice to the new slice .
Code display :
package main
import (
"fmt"
)
func main() {
sliceOne := []string{"a", "b"}
fmt.Printf(" Before slice expansion ")
fmt.Printf(" The length of the slice :%d\n",len(sliceOne))
fmt.Printf(" The volume of the slice :%d\n",cap(sliceOne))
t := make([]string, len(sliceOne), (cap(sliceOne))*2)
copy(t, sliceOne)
sliceOne = t
fmt.Printf(" After slicing and volume expansion ")
fmt.Printf(" The length of the slice :%d\n",len(sliceOne))
fmt.Printf(" The volume of the slice :%d\n",cap(sliceOne))
}Result display :
The length of the slice :2
The volume of the slice :2
The length of the slice :2
The volume of the slice :4
From the code result, we can see that the length of the new slice is 2, Capacity is 4, It is also verified that the length of the slice depends on how many elements are stored , The capacity of the slice depends on the number of elements stored plus the number of remaining positions .
summary
go In language slice The application and use of is relatively convenient and fast , But there are also some small dark pits waiting to be discovered and sorted out ~ In the future, I will write in my blog , Continue to post about go Used in language tips And skills ~
Welcome to pay attention to like 、 Collection 、 Comment on ~~

边栏推荐
- Acwing weekly contest 57- digital operation - (thinking + decomposition of prime factor)
- VMware virtual machine PE startup
- 管理系统-ITclub(下)
- Golang uses regularity to match substring functions
- [LeetCode]161. Edit distance of 1
- Hash table - sum of arrays
- MONTHS_BETWEEN函数使用
- Interview question 3 of software test commonly used by large factories (with answers)
- mysql 大于 小于 等于符号的表示方法
- Go from introduction to practice - error mechanism (note)
猜你喜欢

Use Fiddler to simulate weak network test (2g/3g)

Management system itclub (medium)

Login credentials (cookie+session and token token)

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

Test birds with an annual salary of 50w+ are using this: JMeter script development -- extension function

《7天学会Go并发编程》第六天 go语言Sync.cond的应用和实现 go实现多线程联合执行

解决本地连接不上虚拟机的问题

渗透学习-靶场篇-dvwa靶场详细攻略(持续更新中-目前只更新sql注入部分)

从学生到工程师的蜕变之路

《7天学会Go并发编程》第7天 go语言并发编程Atomic原子实战操作含ABA问题
随机推荐
Ellipsis after SQLite3 statement Solutions for
OpenSSL Programming II: building CA
[LeetCode]513. Find the value in the lower left corner of the tree
二维数组中修改代价最小问题【转换题意+最短路径】(Dijkstra+01BFS)
The karsonzhang/fastadmin addons provided by the system reports an error
管理系统-ITclub(中)
[Sword Offer II]剑指 Offer II 029. 排序的循环链表
管理系统-ITclub(上)
管理系統-ITclub(下)
使用sqlite3语句后出现省略号 ... 的解决方法
Solution to the error of VMware tool plug-in installed in Windows 8.1 system
This set of steps for performance testing using JMeter includes two salary increases and one promotion
[LeetCode]30. Concatenate substrings of all words
[leetcode] dynamic programming solution split integer i[silver fox]
crontab定时任务常用命令
Système de gestion - itclub (II)
Yarn performance tuning of CDH cluster
单元测试界的高富帅,Pytest框架,手把手教学,以后测试报告就这么做~
渗透学习-sql注入过程中遇到的问题-针对sort=left(version(),1)的解释-对order by后接字符串的理解
YOLOv6:又快又准的目标检测框架开源啦