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

边栏推荐
- MONTHS_BETWEEN函数使用
- 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?
- Go from introduction to practice -- definition and implementation of behavior (notes)
- Macro task and micro task understanding
- [LeetCode]515. Find the maximum value in each tree row
- 管理系统-ITclub(上)
- 渗透学习-sql注入过程中遇到的问题-针对sort=left(version(),1)的解释-对order by后接字符串的理解
- 对话乔心昱:用户是魏牌的产品经理,零焦虑定义豪华
- Système de gestion - itclub (II)
- 记一次List对象遍历及float类型判断大小
猜你喜欢

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

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)

Read write separation master-slave replication of MySQL
![[leetcode] dynamic programming solution partition array ii[arctic fox]](/img/a1/4644206db3e14c81f9f64e4da046bf.png)
[leetcode] dynamic programming solution partition array ii[arctic fox]

VMware virtual machine PE startup

美团20k软件测试工程师的经验分享

I think I should start writing my own blog.

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

《7天学会Go并发编程》第六天 go语言Sync.cond的应用和实现 go实现多线程联合执行
随机推荐
管理系统-ITclub(上)
Read write separation master-slave replication of MySQL
【MySQL】数据库函数通关教程下篇(窗口函数专题)
Start the start php
This set of steps for performance testing using JMeter includes two salary increases and one promotion
Example of using gbase 8A OLAP function group by grouping sets
使用Fiddler模拟弱网测试(2G/3G)
信通院举办“业务与应用安全发展论坛” 天翼云安全能力再获认可
Summary of gbase 8A database user password security related parameters
Go from introduction to actual combat - execute only once (note)
gomock mockgen : unknown embedded interface
[LeetCode]100. Same tree
Codeforces Round #721 (Div. 2)
Windwos 8.1系统安装vmware tool插件报错的解决方法
MySQL greater than less than or equal to symbol representation
. Net learning notes (V) -- lambda, LINQ, anonymous class (VaR), extension method
[MySQL practice] query statement demonstration
Remote invocation of microservices
[LeetCode]508. 出现次数最多的子树元素和
Codeforces Round #719 (Div. 3)