当前位置:网站首页>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-07-28 09:36:00 【Twilight drainage software】
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
",reflect.ValueOf(sliceOne).String())
fmt.Printf(" Use make Function created slice:%s
",reflect.ValueOf(sliceTwo).String())
fmt.Printf(" Use make Function created slice:%s
",reflect.ValueOf(sliceThree).String())
}
Program output :
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 0
2、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
",len(strings))
fmt.Printf(" The volume of the slice :%d
",cap(strings))
}
Code result output :
The length of the slice :1
The volume of the slice :2
Code 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 slicepanic: 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
",len(sliceOne))
fmt.Printf(" The volume of the slice :%d
",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
",len(sliceOne))
fmt.Printf(" The volume of the slice :%d
",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 ~~

边栏推荐
- sql server 的关键字在哪张系统表?
- 19c sysaux tablespace sqlobj$plan table is too large. How to clean it up
- Detailed introduction of v-bind instruction
- ARouter源码解析(三)
- 使用Xposed对软件进行破解
- 力扣376-摆动序列——贪心
- The cooperation between starfish OS and metabell is just the beginning
- [multithreading] the underlying principle of println method
- 376. Swing sequence [greedy, dynamic planning -----]
- OpenShift 4 - 使用 VerticalPodAutoscaler 优化应用资源 Request 和 Limit
猜你喜欢

QT basic hand training applet - simple calculator design (with source code, analysis)

JDBC connection database

RGB-T追踪——【多模态融合】Visible-Thermal UAV Tracking: A Large-Scale Benchmark and New Baseline

Conditions and procedures of stock index futures account opening
![[high number] high number plane solid geometry](/img/fc/da6aefed48f4adbaf58995b5e8fa46.png)
[high number] high number plane solid geometry

ECCV 2022 | 无需微调即可推广!基于配准的少样本异常检测框架

mysql 最大建议行数2000w,靠谱吗?

oracle 创建用户且只有查询权限

376. 摆动序列【贪心、动态规划------】

使用Xposed对软件进行破解
随机推荐
正负数值的正则表达式
译文推荐 | 调试 BookKeeper 协议 - 无界 Ledger
ActivityRouter源码解析
MySQL中各类型文件详解
2022 examination question bank and simulation examination of crane driver (limited to bridge crane)
5 operators, expressions, and statements
Detailed introduction of v-bind instruction
[swintransformer source code reading II] window attention and shifted window attention
Regular expressions are hexadecimal digits?
LinkedList内部原理解析
[multithreading] non atomic agreement of long and double
负数的十六进制表示
【AUTOSAR-RTE】-2-Composition,Component和VFB的介绍
IT行业数据与应用关系的变迁
2022 high voltage electrician examination simulated 100 questions and simulated examination
Express builds a simple local background (1)
IJCAI 2022 | the latest overview of graph structure learning: research progress and future prospects
[vscode] vscode usage
How does gbase 8A use preprocessing to quickly insert data?
如何在多线程环境下使用 GBase C API ?