当前位置:网站首页>[go ~ 0 to 1] the third day June 27 slice, map and function
[go ~ 0 to 1] the third day June 27 slice, map and function
2022-06-28 08:26:00 【Autumn sunset】
1. section
1.1 Definition of slice
The slice points to an array at the bottom
1.2 The length of the slice
The length of the slice is equal to the number of slice elements
1.3 The volume of the slice
The capacity of the slice is the number of the underlying array from the first element to the last element of the slice
// By default The length of the slice == Capacity
s1 := []int{
1, 2, 3}
fmt.Printf(" The length of the current slice %d Section capacity %d", len(s1), cap(s1))
1.4 The meaning of slice existence
stay Go in , Once the array is created , The size is fixed dui Method to change the length of an array So we have slices
At the bottom of the slice is a dynamic array You can dynamically add... To the array , Remove elements
Similar to Java The set in
1.5 Create a slice
1.5.1 Mode one : The number of elements is used as the default capacity and length
// By default The length of the slice == Capacity
s1 := []int{
1, 2, 3}
1.5.2 Mode two : Specify slice capacity size and length
// Specify the capacity and length of the slice
ss1 := make([]int, 3, 5)
fmt.Printf(" The length of the current slice %d Section capacity %d", len(ss1), cap(ss1))
1.5.3 Mode three : Create... From an array
// Create slices in three ways :
// First create an array
a1 := [...]int{
1, 2, 3}
// Convert array to slice
sa1 := a1[0:len(a1)]
fmt.Printf(" The length of the current slice %d Section capacity %d", len(sa1), cap(sa1))
2. Slice expansion
The slice is expanded to the last time Capacity *2 When the element length >
2.1 append increase Elements
// By default The length of the slice == Capacity
s1 := []int{
1, 2, 3}
fmt.Printf(" The length of the current slice %d Section capacity %d", len(s1), cap(s1))
// Add an element Slice capacity will increase 2 times The length will increase by one
s1 = append(s1, 4)
fmt.Printf(" The length of the current slice %d Section capacity %d", len(s1), cap(s1))
2.2. The expansion mechanism of slice
1、 When the required capacity is more than twice the size of the original slice , Will use the required capacity as the new capacity .
2、 When the length of the original slice is less than 1024 when , The volume of the new slice will double directly . When the capacity of the original slice is greater than or equal to 1024 when , It will increase again and again 25%, Until the new capacity exceeds the required capacity .
None of the above is accurate Capacity after calculation Also consider the efficient use of memory , Memory alignment
2.2. 1 Capacity required > old * 2 be New capacity = need
// The situation a : If the required capacity is greater than the current capacity *2
s1 := []int{
0}
fmt.Printf(" The length of the original slice %d Section capacity %d \n", len(s1), cap(s1))
s1 = append(s1, 1, 2, 3)
fmt.Printf(" The length of the new slice %d Section capacity %d \n", len(s1), cap(s1))
// Output results The length of the original slice 1 Section capacity 1
// The length of the new slice 4 Section capacity 4
2.2.2 Capacity required < old * 2 And old < 1024 be New capacity = Original capacity * 2
// Scenario two : If the required capacity Less than Current capacity * 2 And Current capacity Less than 1024
s1 := make([]int, 99, 100) // The original capacity is greater than 1024 be The expansion rule is oldcap = oldcap *2 The result should be 200
fmt.Printf(" The length of the original slice %d Section capacity %d \n", len(s1), cap(s1))
s1 = append(s1, 1, 2, 3)
fmt.Printf(" The length of the new slice %d Section capacity %d \n", len(s1), cap(s1)) // The actual result is 200
2.2.3 Capacity required < old * 2 And old > 1024 be New capacity = Original capacity * 1.25
// Scenario two : If the required capacity Less than Current capacity * 2 And Current capacity Less than 1024
s1 := make([]int, 1022, 1024) // The original capacity is greater than 1024 be The expansion rule is oldcap = oldcap *1.5 The result should be 1536
fmt.Printf(" The length of the original slice %d Section capacity %d \n", len(s1), cap(s1))
s1 = append(s1, 1, 2, 3)
fmt.Printf(" The length of the new slice %d Section capacity %d \n", len(s1), cap(s1)) // The actual result is 1536
3. Slice and copy
s1 := []int{
1, 2, 3}
s2 := make([]int, 2, 2)
copy(s2, s1) // Parameter one : Destination Parameter two : source
fmt.Println(s2)
When slice copying The element will be copied according to the slice length of the copied element As shown in the above code
be s2 The result of printing is 1,2
4. Get the memory address value and the corresponding value
stay Go In language non-existent Operation of pointer There are two symbols related to memory Need to remember
4.1 ’ & ’ Get the object memory address value
s1 := 10
fmt.Printf("s1 The memory address of is %v", &s1)
4.2 ’ * ’ Get the value according to the memory address value
mt.Printf(" Value according to memory address %v", *(&s1))
5. new Functions and make Function usage
Both are used to apply for memory addresses but There's a difference
new It is mainly used to apply for memory addresses for basic data types and make It's for slice, map , chan Apply for memory address
4. map Use
4.1 map Of establish
// Create a map
m := make(map[string]int)
// Create a map
m := make(map[string]int,[ Capacity size ])
4.2 map add value
m[" Zhang San "] = 19
m[" Li Si "] = 20
m[" Wang Wu "] = 21
4.3 map Traverse
4.3.1 Traverse key,value
// Traverse :
for key, value := range m {
fmt.Printf("%v ---- %v \n", key, value)
}
4.3.2 Traverse key
// Traverse key
for key, _ := range m {
fmt.Println(key)
}
4.3.3 Traverse value
// Traverse value
for _, value := range m {
fmt.Println(value)
}
4.4 according to key Delete value
// according to key Delete value
delete(m," Zhang San ")
4.5 Judge key Whether there is
Use by convention ok Identify a key Whether there is
// Judge key Whether there is
i, ok := m[" Zhang San 1"]
if !ok {
fmt.Printf("%v There is no current key \n", m)
} else {
fmt.Printf(" At present key The corresponding value is %v \n", i)
}
5. function
5.1 What is a function
Function to encapsulate the code Extract a piece of code , Give it a name Each time you use it, you only need to call the function name Improved code utilization
5.2 Definition of function
func mymethod(x int, y int) (ret int) {
return x + y
}
matters needing attention :
If the number of consecutive parameter types in the formal parameter list is the same , Just write the type of the last parameter , The types of other parameters can be omitted
If We named the return value ( Equivalent to declaring a local variable ), You can write one directly return
func mymethod1(x,y int)(sum int) {
sum = x + y
return
}
- Multiple return values , You can also name the return value
func mymethod1(x, y int) (sum int, del int) {
sum = x + y
del = x - y
return
}
5.3 Anonymous functions
If we want to use a function only once , Then you can use anonymous functions
// An anonymous function is assigned to a variable
mn1 := func(x, y int) (int) {
return x + y
}
fmt.Println(mn1(1, 9))
5.4 Global anonymous function
// Global anonymous functions Assign to a variable
var (
m = func(x, y int) int {
return x + y
}
)
end practice
1. Count the number of times each word appears in a string . such as :”how do you do” in how=1 do=2 you=1
str := "what do you want do what"
split := strings.Split(str, " ")
// Traverse Character slices Go to map Collection save
m1 := make(map[string]int)
for _, word := range split {
// Determine whether the string already exists
_, ok := m1[word]
if !ok {
// non-existent
m1[word] = 1
} else {
// Already exist
m1[word] = m1[word] + 1
}
}
// Print the results
fmt.Println(m1)
边栏推荐
- FFMpeg (一) av_register_all()
- duilib 入门基础十二 样式类
- Trigonometric transformation formula
- Discussion on the application of GIS 3D system in mining industry
- Eslint 语法监测关闭
- Prometheus monitoring (I)
- Trailing Zeroes (II)
- js运算符的优先级
- Redis deployment under Linux & redis startup
- In flood fighting and disaster relief, the city donated 100000 yuan of love materials to help Yingde
猜你喜欢

ROS 笔记(08)— 服务数据的定义与使用

WasmEdge 0.10.0 发布!全新的插件扩展机制、Socket API 增强、LLVM 14 支持

探讨gis三维系统在矿山行业中的应用

块级元素上下左右居中的两个小技巧

Idea related issues

图像翻译:UVCGAN: UNET VISION TRANSFORMER CYCLE-CONSISTENT GAN FOR UNPAIRED IMAGE-TO-IMAGE TRANSLATION
![Dell r730 server startup error: [xxx] USB 1-1-port4: disabled by hub (EMI?), re-enabling...](/img/90/425965ca4b3df3656ce2a5f4230c4b.jpg)
Dell r730 server startup error: [xxx] USB 1-1-port4: disabled by hub (EMI?), re-enabling...

Devops Basics: Jenkins deployment and use (I)

Chenglian premium products donated love materials for flood fighting and disaster relief to Yingde

AI chief architect 8-aica-gao Xiang, in-depth understanding and practice of propeller 2.0
随机推荐
Is it reliable for the top ten securities companies to register and open accounts? Is it safe?
Sword finger offer 30 Stack containing min function
Oracle view all tablespaces in the current library
Prometheus service discovery
Selenium+chromedriver cannot open Google browser page
B_QuRT_User_Guide(26)
NPM clean cache
ROS 笔记(09)— 参数的查询和设置
The Falling Leaves
【学习笔记】拟阵
整数划分
B_QuRT_User_Guide(27)
【学习笔记】搜索
Force buckle 1024 video splicing
The preliminary round of the sixth season of 2022 perfect children's model Foshan competition area came to a successful conclusion
Solve NPM err! Unexpected end of JSON input while parsing near
Preparation for Oracle 11g RAC deployment on centos7
Introduction to kubernetes (I)
B_QuRT_User_Guide(28)
Installing MySQL under Linux