当前位置:网站首页>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 ~~

边栏推荐
- Introduction to ARCS Model
- [leetcode] dynamic programming solution split integer i[silver fox]
- Crontab scheduled task common commands
- 管理系統-ITclub(下)
- average-population-of-each-continent
- Experience sharing of meituan 20K Software Test Engineers
- 【mysql实战】查询语句实战演示
- 渗透学习-靶场篇-dvwa靶场详细攻略(持续更新中-目前只更新sql注入部分)
- [leetcode] 508. Élément de sous - arbre le plus fréquent et
- [LeetCode]动态规划解分割数组I[Red Fox]
猜你喜欢
扁平数组和JSON树的转换

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

年薪50W+的测试大鸟都在用这个:Jmeter 脚本开发之——扩展函数

This set of steps for performance testing using JMeter includes two salary increases and one promotion

Figure countdownlatch and cyclicbarrier based on AQS queue

C language programming detailed version (learning note 1) I can't understand it after reading, and I can't help it.

管理系统-ITclub(下)

真香,自从用了Charles,Fiddler已经被我彻底卸载了

Open source technology exchange - Introduction to Chengying, a one-stop fully automated operation and maintenance manager

管理系统-ITclub(中)
随机推荐
The karsonzhang/fastadmin addons provided by the system reports an error
真香,自从用了Charles,Fiddler已经被我彻底卸载了
[MySQL practice] query statement demonstration
The problem of minimum modification cost in two-dimensional array [conversion question + shortest path] (dijkstra+01bfs)
Slow bear market, bit Store provides stable stacking products to help you cross the bull and bear
[leetcode] dynamic programming solution split integer i[silver fox]
Acwing week 57 longest continuous subsequence - (binary or tree array)
Professor of Tsinghua University: software testing has gone into a misunderstanding - "code is necessary"
[LeetCode]100. Same tree
mysql 大于 小于 等于符号的表示方法
[LeetCode]30. Concatenate substrings of all words
I think I should start writing my own blog.
C language programming detailed version (learning note 1) I can't understand it after reading, and I can't help it.
It smells good. Since I used Charles, Fiddler has been completely uninstalled by me
渗透学习-靶场篇-pikachu靶场详细攻略(持续更新中-目前只更新sql注入部分)
[leetcode] dynamic programming solution partition array ii[arctic fox]
Analysis of stone merging
Remote invocation of microservices
[LeetCode]508. The most frequent subtree elements and
Fill in the blank of rich text test