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

边栏推荐
- crontab定时任务常用命令
- 如何做好功能测试?你确定不想知道吗?
- MONTHS_ Between function use
- How to open an account for agricultural futures? How much is the handling charge for opening an account for futures? Who can give you a preferential handling charge?
- 使用Jmeter进行性能测试的这套步骤,涨薪2次,升职一次
- Interval DP of Changyou dynamic programming
- MONTHS_BETWEEN函数使用
- Bean paste green protects your eyes
- 軟件測試自動化測試之——接口測試從入門到精通,每天學習一點點
- Management system itclub (Part 2)
猜你喜欢

Codeforces Round #716 (Div. 2)

【Redis】零基础十分钟学会Redis

Codeforces Round #719 (Div. 3)

二维数组中修改代价最小问题【转换题意+最短路径】(Dijkstra+01BFS)

Slow bear market, bit Store provides stable stacking products to help you cross the bull and bear
![[LeetCode]动态规划解分割数组I[Red Fox]](/img/b2/df87c3138c28e83a8a58f80b2938b8.png)
[LeetCode]动态规划解分割数组I[Red Fox]

Do280openshift access control -- Security Policy and chapter experiment

AQS SOS AQS with me

管理系统-ITclub(下)

對話喬心昱:用戶是魏牌的產品經理,零焦慮定義豪華
随机推荐
Typescript learning
Test birds with an annual salary of 50w+ are using this: JMeter script development -- extension function
Fill in the blank of rich text test
Beijing University of Posts and Telecommunications - multi-agent deep reinforcement learning for cost and delay sensitive virtual network function placement and routing
Go from introduction to practice - error mechanism (note)
[LeetCode]动态规划解分割数组I[Red Fox]
A method of go accessing gbase 8A database
北京邮电大学|用于成本和延迟敏感的虚拟网络功能放置和路由的多智能体深度强化学习
从学生到工程师的蜕变之路
Open source technology exchange - Introduction to Chengying, a one-stop fully automated operation and maintenance manager
VMware virtual machine PE startup
真香,自从用了Charles,Fiddler已经被我彻底卸载了
[LeetCode]515. Find the maximum value in each tree row
登录凭证(cookie+session和Token令牌)
. Net learning notes (V) -- lambda, LINQ, anonymous class (VaR), extension method
Windwos 8.1系统安装vmware tool插件报错的解决方法
Interview question 3 of software test commonly used by large factories (with answers)
The create database of gbase 8A takes a long time to query and is suspected to be stuck
Introduction to ARCS Model
Go from introduction to actual combat - only any task is required to complete (notes)