当前位置:网站首页>[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)
边栏推荐
- Discussion on the application of GIS 3D system in mining industry
- Devops Basics: Jenkins deployment and use (I)
- Selenium+chromedriver cannot open Google browser page
- Map. ToCharArray( ),Map. getOrDefault(). Map. charAt()
- Kali installation configuration
- 11grac turn off archive log
- The micro kernel zephyr is supported by many manufacturers!
- B_QuRT_User_Guide(30)
- 为什么函数模板没有偏特化?
- [learning notes] simulation
猜你喜欢

About using font icons in placeholder

Why MySQL cannot insert Chinese data in CMD

B_ QuRT_ User_ Guide(26)

App automated testing appium Tutorial Part 1 - advanced supplementary content

ROS notes (09) - query and setting of parameters

Redis02 -- an operation command of five data types for ending redis (it can be learned, reviewed, interviewed and collected for backup)

Trigonometric transformation formula

Usage record of Xintang nuc980: self made development board (based on nuc980dk61yc)

【学习笔记】拟阵

抗洪救灾,共克时艰,城联优品捐赠10万元爱心物资驰援英德
随机推荐
Discussion on the application of GIS 3D system in mining industry
Redis02 -- an operation command of five data types for ending redis (it can be learned, reviewed, interviewed and collected for backup)
PC端隐藏滚动条
[learning notes] simulation
Kubernetes notes and the latest k3s installation introduction
About using font icons in placeholder
[learning notes] search
[learning notes] linear basis
In flood fighting and disaster relief, the city donated 100000 yuan of love materials to help Yingde
Priority of JS operator
Leetcode摆动序列系列
[learning notes] differential constraint
Redis deployment under Linux & redis startup
新唐NUC980使用记录:自制开发板(基于NUC980DK61YC)
Solve NPM err! Unexpected end of JSON input while parsing near
【力扣10天SQL入门】Day4 组合查询 & 指定选取
RAC enable archive log
2022巴黎时装周儿童单元6.19武汉站圆满落幕
Resolution of Rac grid failure to start after server restart
设置网页的标题部分的图标