当前位置:网站首页>[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)
边栏推荐
- Leetcode摆动序列系列
- 城联优品向英德捐赠抗洪救灾爱心物资
- Why are function templates not partial specialization?
- Modifying the SSH default port when installing Oracle RAC makes CRS unable to install
- 2022第六季完美童模 佛山赛区 初赛圆满落幕
- Unity - use of API related to Pico development input system ---c
- 抗洪救灾,共克时艰,城联优品捐赠10万元爱心物资驰援英德
- 图像翻译/Transformer:ITTR: Unpaired Image-to-Image Translation with Transformers用Transfor进行非配对图像对图像的转换
- Almost Union-Find(带权并查集)
- Not so Mobile
猜你喜欢

Kali installation configuration

Little artist huangxinyang was invited to participate in the Wuhan station of children's unit of Paris Fashion Week

B_ QuRT_ User_ Guide(26)

AWS saves data on the cloud (3)

广州:金融新活水 文企新机遇

After installing NRM, the internal/validators js:124 throw new ERR_ INVALID_ ARG_ TYPE(name, ‘string‘, value)

Infinite penetration test

【学习笔记】拟阵

B_QuRT_User_Guide(27)

Set the encoding of CMD to UTF-8
随机推荐
How to choose an account opening broker? Is it safe to open an account online?
抗洪救灾,共克时艰,城联优品捐赠10万元爱心物资驰援英德
Unity 获取当前物体正前方,一定角度、距离的坐标点
PLSQL installation under Windows
11grac turn off archive log
【学习笔记】模拟
Installing MySQL under Linux
Modifying the SSH default port when installing Oracle RAC makes CRS unable to install
Solve NPM err! Unexpected end of JSON input while parsing near
NPM clean cache
Leetcode swing series
cuda和cudnn和tensorrt的理解
Do you know TCP protocol (2)?
AWS builds a virtual infrastructure including servers and networks (2)
js取整的小技巧
RAC enable archive log
Map. ToCharArray( ),Map. getOrDefault(). Map. charAt()
Unity gets the coordinate point in front of the current object at a certain angle and distance
【Go ~ 0到1 】 第二天 6月25 Switch语句,数组的声明与遍历
JS rounding tips