当前位置:网站首页>Go language go language built-in container
Go language go language built-in container
2022-07-25 20:15:00 【Ding Jiaxiong】
Go Language
List of articles
6. Go Language built-in container
Go The built-in container of language mainly includes arrays 、 Slicing and Mapping .
6.1 Array
An array is a sequence of data items with the same type and fixed length , This set of data item sequence is stored in a continuous area of memory .
The element type stored in the array can be integer 、 String or other custom types . Arrays need to be declared before use , When declaring, you must specify the size of the array, and the size of the array cannot be changed later .
Subscript from 0 Start .
6.1.1 Declaration array
var Array variable name [ The length of the array ] Element type
package main
import "fmt"
func main() {
var student [3]string
fmt.Println(student)
}

6.1.2 Initialize array
Assignment on declaration
var student = [3]string{
"Tom","Ben","Peter"}
If you ignore the numbers in brackets , Do not set the array size ,Go The language compiler can also set the size of the array according to the number of elements when compiling , By using “…” Instead of array size
var student = [...]string{
"Tom","Ben","Peter"}
package main
import "fmt"
func main() {
var student = [...]string{
"Tom", "Ben", "Peter"}
fmt.Println(student)
}

6.1.3 range keyword
range yes Go A very common keyword in language , Its main function is to cooperate for Keyword iterate over array and data structures such as slicing and mapping, which will be introduced later .
package main
import "fmt"
func main() {
var num = [...]int{
1, 2, 3, 4}
for k, v := range num {
fmt.Println(" Variable k:", k, " ", " Variable v:", v)
}
}

range The following expression is called range expression , At iteration time , keyword range Two values will be returned , By the variable k and v receive . among k Is the index position to which the current loop iterates ,v Is a copy of the element value corresponding to this position .
| range expression | The first return value | The second return value |
|---|---|---|
| Array | Element subscript | Element value |
| section | Element subscript | Element value |
| mapping | key | value |
| passageway | Elements | N/A |
6.1.4 Traversal array
for Loop traversal
package main
import "fmt"
func main() {
var student = [...]string{
"Tom", "Ben", "Peter"}
for k, v := range student {
fmt.Println(" The array subscript :", k, ", The corresponding element :", v)
}
}

6.2 section
Relative to the array , section (slice) It is a more convenient and powerful data structure , It also represents a continuous set of multiple elements of the same type , But the slice itself does not store any elements , It's just a reference to an existing array .
Slice structure
- Address : The address of the slice generally refers to the memory address pointed to by the first element in the slice , Hexadecimal
- length : The number of actual elements in the slice
- Capacity : The number from the starting element of the slice to the last element in its underlying array
Three slice generation methods
- Generate a new slice from the array
- Generate a new slice from the slice
- Directly generate a new slice
6.2.1 Generate a new slice from the array
slice [ Starting position : End position ]
Use len() Function to get the current slice length ,cap() Function to obtain the current slice capacity .
package main
import "fmt"
func main() {
var student = [...]string{
"Tom", "Ben", "Peter"}
var student1 = student[1:2]
fmt.Println("student Array :", student)
fmt.Println("student1 section :", student1)
fmt.Println("student The array address is ", &student[1])
fmt.Println("student1 The slice address is ", &student1[0]) // Address of element
fmt.Println("student1 Slice length is :", len(student1))
fmt.Println("student1 The slice capacity is :", cap(student1))
}

According to the results of operation , Generating new slices from arrays or slices has the following features :
- The length of the newly generated slice : End position - Starting position
- The element extracted from the newly generated slice does not include the element corresponding to the end position
- The newly generated slice is a reference to an existing array or slice , Its address is the same as the element address corresponding to the start position of the intercepted array or slice .
- The newly generated slice capacity refers to the number from the starting element of the slice to the last element in its underlying array
6.2.2 Generate a new slice from the slice
slice[:] To represent the slice itself
package main
import "fmt"
func main() {
var student = [...]string{
"Tom", "Ben", "Peter"}
var student1 = student[1:3]
var student2 = student[0:1]
fmt.Println("student Array :", student[:])
fmt.Println("student1 section :", student1[:])
fmt.Println("student2 section :", student2[:])
fmt.Println("student The array address is :", &student[1])
fmt.Println("student1 The slice address is :", &student1[0])
fmt.Println("student2 The slice address is :", &student2[0])
fmt.Println("student1 Slice length is :", len(student1))
fmt.Println("student1 The slice capacity is :", cap(student1))
fmt.Println("student2 Slice length is :", len(student2))
fmt.Println("student2 The slice capacity is :", cap(student2))
}

6.2.3 Directly generate a new slice
Declaration slice
var Slice variable name [] Element typepackage main import "fmt" func main() { var student []int fmt.Println("student section ", student) fmt.Println("student Section length :", len(student)) fmt.Println("student Section capacity :", cap(student)) fmt.Println(" determine student Whether the slice is empty :", student == nil) }
After the slice declaration, its content is empty , The length and capacity are 0.
Initialization slice
Initialize while declaring
package main import "fmt" func main() { var student = []string{ "Tom", "Ben", "Peter"} fmt.Println("student section :", student) fmt.Println("student Section length :", len(student)) fmt.Println("student Section capacity :", cap(student)) fmt.Println(" determine student Whether the slice is empty :", student == nil) }
Use make() Function initialization
After declaring the slice , You can do this with built-in functions make() To initialize the slice .
make([] Element type , Section length , Section capacity )The capacity value of the slice must be greater than or equal to the slice length value , Otherwise, the program will report an error . There should be a rough estimate of the capacity of the slice , If the capacity value is too small , Multiple expansion of slices will cause performance loss .
package main import "fmt" func main() { var student []int student = make([]int, 2, 10) fmt.Println("student section :", student) fmt.Println("student Section length :", len(student)) fmt.Println("student Section capacity :", cap(student)) fmt.Println(" determine student Whether the slice is empty :", student == nil) }
6.2.4 Add elements to the slice
Use append() Function to add elements to the slice .
When the slice can no longer hold other elements ( That is, the current slice length value is equal to the capacity value ), Next time use append() Function to add elements to the slice , Capacity will be 2 Multiple expansion .
package main
import "fmt"
func main() {
student := make([] int , 1, 1)
for i := 0 ; i < 8 ; i ++{
student = append(student,i)
fmt.Println(" Current slice length :",len(student)," Current slice capacity :",cap(student))
}
}

package main
import "fmt"
func main() {
var student = [...]string{
"Tom", "Ben", "Peter"}
var student1 = student[0:1] // from student Array generation slice student1
fmt.Println("student Array :", student)
fmt.Println("student section :", student1)
student1 = append(student1, "Danny") // Yes student1 Sliced elements are added , It will overwrite the elements corresponding to the reference array
fmt.Println(" expand Danny After student1 section :", student1, ", Slice length is :", len(student1), " The slice capacity is :", cap(student1))
fmt.Println(" expand Danny After student Array :", student)
}

because student1 Slicing is from student Array generation ( to student References to arrays ), by student1 Adding elements will overwrite student The corresponding element in the array .
So → If slices are generated from other arrays or slices , The addition of new slice elements needs to consider the impact on the data in the original array or slice .
6.2.5 Delete element from slice
Go The language does not provide a method for deleting slice elements , Therefore, you need to manually connect the elements before and after the deletion point , So as to delete the elements in the slice .
package main
import "fmt"
func main() {
var student = []string{
"Tom", "Ben", "Peter", "Danny"}
student = append(student[0:1], student[2:]...) // This sentence is equivalent to student = append(student[0:1],student[2],student[3])
fmt.Println("student section :", student)
fmt.Println("student Section length :", len(student))
fmt.Println("student Section capacity :", cap(student))
}
Empty the slice , You can set the start and end subscripts of the slice to 0 Realization
package main
import "fmt"
func main() {
var student = []string{
"Tom", "Ben", "Peter", "Danny"}
student = student[0:0]
fmt.Println("student section :", student)
fmt.Println("student Section length :", len(student))
fmt.Println("student Section capacity :", cap(student))
}

6.2.6 Traversing slices
The traversal of slices is similar to that of arrays , You can traverse by slicing subscripts . The slice subscript is also from 0 Start .
6.3 mapping
mapping (map) Is an unordered set of key value pairs ,map The key of is similar to the index , The value that points to the data . When the program needs to store related data , It is often used map.
country := map[string]string{
" China ":"China",
" The United States ":"America",
" Japan ":"Japan",
}
6.3.1 The statement mapping
var map [ Key type ] Value type
package main
import "fmt"
func main() {
var studentScoreMap map[string]int
fmt.Println(studentScoreMap)
}

6.3.2 Initialize mapping
Initialize while declaring
package main import "fmt" func main() { var studentScoreMap = map[string]int{ "Tom": 80, "Ben": 85, "Peter": 90, } fmt.Println(studentScoreMap) }
Use make() Function initialization
Similar to initialization of slices ,map You can also use make() Function to initialize .
make(map[ Key type ] Value type ,map Capacity )Use make() Function initialization map You may not specify map Capacity , But for map Multiple expansion of will cause performance loss .
cap() Function can only be used to get the capacity of slices , Can't get map The capacity of , Can pass len() Function to obtain map The current length of .
package main import "fmt" func main() { var studentScoreMap map[string]int studentScoreMap = make(map[string]int) studentScoreMap["Tom"] = 80 studentScoreMap["Ben"] = 85 studentScoreMap["Peter"] = 90 fmt.Println("map The length is :", len(studentScoreMap)) fmt.Println(studentScoreMap) }
6.3.3 Traversal mapping
map Traversal of mainly through for Loop through , When traversing, you can get map The bond and the value of .
package main
import "fmt"
func main() {
var studentScoreMap map[string]int
studentScoreMap = make(map[string]int)
studentScoreMap["Tom"] = 80
studentScoreMap["Ben"] = 85
studentScoreMap["Peter"] = 90
for k, v := range studentScoreMap {
fmt.Println(k, v)
}
}

Traverse keys only
for k := range studentScoreMap{
fmt.Println(k)
}
Traversal values only
for _,v := range studentScoreMap{
fmt.Println(v)
}
6.3.4 Remove key value pairs from the map
Go Language passing delete() Function to map Delete the specified key value pair in .
delete(map, key )
delete() The function will directly delete the specified key value pair , Instead of just deleting keys or values .
Go Language is not for map Provides a way to empty all elements , Want to empty map The only way is to redefine a new map.
6.5 Knowledge development
Concurrent operations map
about map, We can define a key and a value , And then from map In order to get 、 Change and delete this value .
If multiple coroutines access one concurrently map, It may cause the program to exit abnormally :
package main func main() { Gomap := make(map[int]int) for i := 0; i < 10000; i++ { go writeMap(Gomap, i, i) go readMap(Gomap, i) } } func readMap(Gomap map[int]int, key int) int { return Gomap[key] } func writeMap(Gomap map[int]int, key int, value int) { Gomap[key] = value }
The reason is that many processes are trying to correct map Write simultaneously .
map It's not Xiecheng safe , There can only be one pair at a time map To operate .
Solution : Use sync Yes map Lock or use directly Go stay 1.9 Thread safety provided in version map.
The essence of locking is that the current coordination process is right map Lock it before operation , After locking, any other processes cannot be matched map Do anything , Until the current collaboration is unlocked .
package main import ( "fmt" "sync" ) var lock sync.RWMutex func main() { GoMap := make(map[int]int) for i := 0; i < 100000; i++ { go writeMap(GoMap, i, i) go readMap(GoMap, i) } fmt.Println("Done") } func readMap(Gomap map[int]int, key int) int { lock.Lock() // Lock m := Gomap[key] lock.Unlock() // Unlock return m } func writeMap(Gomap map[int]int, key int, value int) { lock.Lock() Gomap[key] = value lock.Unlock() }
Locking has a certain impact on program performance , Use sync.Map
characteristic
- Internally, the impact of locking on performance is reduced through redundant data structures .
- There is no need to initialize before use , A direct statement is enough .
- sync.Map Don't use map To read and assign values
package main import ( "fmt" "sync" ) func main() { var GoMap sync.Map for i := 0; i < 100000; i++ { go writeMap(GoMap, i, i) go readMap(GoMap, i) } fmt.Println("Done") } func readMap(Gomap sync.Map, key int) int { res, ok := Gomap.Load(key) // Thread safe read if ok == true { return res.(int) } else { return 0 } } func writeMap(Gomap sync.Map, key int, value int) { Gomap.Store(key, value) // Thread safety settings }
【 Be careful 】
- sync.Map No need to use make establish
- Load() The first return value of the method is the interface type , It needs to be converted to map The type of value
- at present sync.Map No access provided map The method of quantity , The solution is to iterate through map.
- And the more common map comparison ,sync.Map To ensure concurrency security , There will be performance loss , So in the case of non concurrency , Recommended map.
边栏推荐
- tga文件格式(波形声音文件格式)
- 【高等数学】【1】函数、极限、连续
- [today in history] July 15: Mozilla foundation was officially established; The first operation of Enigma cipher machine; Nintendo launches FC game console
- Prescan quick start to master Lesson 19: prescan actuator configuration, track synchronization and non configuration of multiple tracks
- 10. < tag dynamic programming and subsequence, subarray> lt.53. maximum subarray and + lt.392. Judge subsequence DBC
- qml 结合 QSqlTableModel 动态加载数据 MVC「建议收藏」
- 数字信息化(先枚举假设,再看是否满足条件)(1089 狼人杀-简单版)
- Network RTK UAV test [easy to understand]
- Pytorch's transforms (numpy data type is converted to tensor, normalized and resized)
- [advanced mathematics] [6] differential calculus of multivariate functions
猜你喜欢

Timing analysis and constraints based on xlinx (1) -- what is timing analysis? What are temporal constraints? What is temporal convergence?
![[advanced mathematics] [6] differential calculus of multivariate functions](/img/9e/84fe6f74b58cbaabab1b6eed0df556.png)
[advanced mathematics] [6] differential calculus of multivariate functions

推荐系统专题 | MiNet:跨域CTR预测

9. < tag dynamic programming and subsequence, subarray> lt.718. Longest repeated subarray + lt.1143. Longest common subsequence
![[today in history] July 17: Softbank acquired arm; The first email interruption; Wikimedia International Conference](/img/0f/8ce2d5487b16d38a152cfd3ab454bb.png)
[today in history] July 17: Softbank acquired arm; The first email interruption; Wikimedia International Conference

How to ensure the quality of customized slip rings

Vivo official website app full model UI adaptation scheme

笔记——记录一个CannotFindDataSourceException: dynamic-datasource can not find primary datasource问题解决

Notes - record a cannotfinddatasourceexception: dynamic datasource can not find primary datasource problem solving

PMP practice once a day | don't get lost in the exam -7.25
随机推荐
推荐系统专题 | MiNet:跨域CTR预测
High number_ Chapter 3 learning experience and summary of multiple integral
Apache MINA框架「建议收藏」
[advanced mathematics] [5] definite integral and its application
Can you tell me whether mindspore supports torchvision Model directly uses the pre trained network, such as vgg16
DIY个人服务器(diy存储服务器)
移动web布局方法
从瞳代到“瞳代”再到品牌,暴利的美瞳的变与未变
统信UOS下配置安装cocos2dx开发环境
Technology cloud report: more than zero trust, the wild hope of Parra's "Digital Security Cloud strategy"
Prescan quick start to master the special functions of prescan track editing in lecture 18
qml 结合 QSqlTableModel 动态加载数据 MVC「建议收藏」
Docker 搭建 Redis Cluster集群
【高等数学】【4】不定积分
Application of conductive slip ring in mechanical equipment
[cloud native | learn kubernetes from scratch] VIII. Namespace resource quotas and labels
wallys//IPQ5018/IPQ6010/PD-60 802.3AT Input Output 10/100/1000M
TGA file format (waveform sound file format)
雷达水位计的工作原理及安装维护注意事项
【高等数学】【5】定积分及应用