当前位置:网站首页>Go learning (II. Built in container)
Go learning (II. Built in container)
2022-06-22 04:47:00 【Soy sauce elder martial brother】
List of articles
2.1 Array
go There are also arrays , Next, let's learn about an array .
2.1.1 Define an array
go There are several ways to define an array :
func main() {
// go Definition of array
var arr1 [3]bool // There is no initial value however go By default, the initial value will be assigned
arr2 := [3]int{
1, 2, 3} // This is another initial value
arr3 := [...]int{
1,2,3,4,5} // This is to determine the number of arrays according to the number defined later
var arr4 [4][5]int // Two dimensional array ,4 That's ok 5 Column
fmt.Println(arr1, arr2, arr3, arr4)
return
}
go Array of , It is also different from other arrays , Is a number in front , Add type after , It's easy to get confused with other languages .
go It also supports two-dimensional arrays , How many rows are the first in a two-dimensional array , How many columns are following
[false false false] [1 2 3] [1 2 3 4 5] [[0 0 0 0 0] [0 0 0 0 0] [0 0 0 0 0] [0 0 0 0 0]]
2.1.2 Array traversal
Next, let's look at the traversal of arrays ,
- The conventional way
for i:=0; i<len(arr2); i++ {
fmt.Println(arr2[i])
}
This traversal based on length is our normal operation .
- range
for i, v := range arr3 {
fmt.Println(i, v)
}
go A keyword is provided ,range, Is to traverse the values of each container , Not just arrays , And the back slice and map. and range The return value of is still interesting , Returns two values , The first is the subscript , The second is the value of the array .
2.1.3 Arrays as function arguments
Let's take a look at the array as a function parameter , How is it transmitted :
- Value passed
func funcarr1(arr [3]int) {
// [3]int Is a type , No follow c Same first address only
arr[0] = 100
}
func main() {
// go Definition of array
var arr1 [3]bool
arr2 := [3]int{
1, 2, 3}
arr3 := [...]int{
1,2,3,4,5}
var arr4 [4][5]int // Two dimensional array ,4 That's ok 5 Column
fmt.Println(arr1, arr2, arr3, arr4)
for i:=0; i<len(arr2); i++ {
fmt.Println(arr2[i])
}
funcarr1(arr2)
for i, v := range arr2 {
fmt.Println(i, v)
}
return
}
According to the printed results , Obviously, this array is just passing values , This is with us c/c++ It's the same , If it is transmitted in this way, it is directly transmitted .
So if this array is large , Is it difficult to copy , So there is an array pointer :
- Pointer passing
func funcarr2(arr *[3]int) {
arr[0] = 100
}
The result of this print is obviously modified , therefore go It can also be passed to an array .
however go Can you use arrays , Actually in go In language , Generally, arrays are not used , Only slices .
2.2 section
go The famous slice of , Actually, I learned slicing , It feels a bit like ArrayList, But it's different , But with the help of ArrayList It is also meaningful to help us learn slicing .
2.2.1 Introduction of slices
arr5 := [...]int{
0,1,2,3,4,5,6,7,8,9}
fmt.Println("s := [2:6]", arr5[2:6])
fmt.Println("s := [:6]", arr5[:6])
fmt.Println("s := [2:]", arr5[2:])
fmt.Println("s := [:]", arr5[:])
Define a arr5 Array of , And then you can use [] Perform various slices , That's an interesting name .
Printed results :
s := [2:6] [2 3 4 5]
s := [:6] [0 1 2 3 4 5]
s := [2:] [2 3 4 5 6 7 8 9]
s := [:] [0 1 2 3 4 5 6 7 8 9]
Just like what we thought , Is a slice of the sensory subscript .
2.2.2 Slice as function parameter
Above, we wrote an array as a function parameter , Because the type of array needs
func funcarr3(arr []int) {
// Do not limit the type
arr[0] = 100
}
func main() {
arr5 := [...]int{
0,1,2,3,4,5,6,7,8,9}
s := arr5[2:6]
fmt.Println(s)
funcarr3(s)
fmt.Println(s)
return
}
When the slice is passed, the size is not required , And slice as a function parameter , It's a quote , Therefore, the values in the array can be modified inside the function .
[2 3 4 5]
[100 3 4 5]
I just wanted to use an array as a parameter , Can you pass values to the slice , But it still doesn't work ,go The type of language is very limited .
2.2.3 Extension of slicing
The teacher came up with a difficult problem :
arr6 := [...]int{
0,1,2,3,4,5,6,7}
s1 := arr6[2:6]
s2 := s1[3:5]
fmt.Println(s1, s2)
s1 and s2 Value , Printed directly :
[2 3 4 5] [5 6]
So we see s2 You can get the value , Why is it so , Actually, this slice has a len, And a cap Of , That is, the underlying implementation of the slice has a maximum capacity cap, There is also a valid data len, We can change the code , Print it out :
arr6 := [...]int{
0,1,2,3,4,5,6,7}
s1 := arr6[2:6]
s2 := s1[3:5]
fmt.Printf("s1=%v len(s1)=%d cap(s1)=%d\n", s1, len(s1), cap(s1))
fmt.Printf("s2=%v len(s2)=%d cap(s2)=%d\n", s2, len(s2), cap(s2))
Print the results :
s1=[2 3 4 5] len(s1)=4 cap(s1)=6
s2=[5 6] len(s2)=2 cap(s2)=3
Does this look like a ArrayList, In fact, it has a capacity , There is also an effective length , So when slicing data , It retains the ability to extend backwards , such s2 To get the value .
If you use append When you add elements , If it exceeds the original array cap, A new and larger underlying array will be allocated , Then copy the value , If no one uses the original array , Just from go Recycle the garbage .
2.2.4 Define slices directly
We usually use it in operation , You should not define an array first , Then change it into sliced , We can define slices directly :
var s3 []int // No value , The value is nil
fmt.Println(s3)
s3 = append(s3, 1)
s4 := []int{
3,4,5}
fmt.Println(s4)
// Know the length , You need to define a slice
s5 := make([]int, 10)
fmt.Println(s5)
// Need to define cap It's OK, too
s6 := make([]int, 10, 20)
fmt.Println(s6)
Directly defined slices have such 4 Ways of planting , However, No. 3 In this way, we will often use , Let's see if it's more like ArrayList 了 .
2.2.5 Slicing operation
Pass the rookie tutorial , We know that in addition to append() There is copy() function .
I don't know any other functions at present , Ha ha ha ha .
2.3 map
go And again map Of , Next, learn to learn map.
2.3.1 Definition
Or just learn one map The definition of :
m := map[string]string {
"name" : "aaa",
"course" : "golang",
"site" : "immoc",
}
fmt.Println(m)
mm := map[string]map[string]string {
"name" : m,
}
fmt.Println(mm)
m2 := make(map[string]int)
m3 := make(map[string]int, 10)
fmt.Printf("m2=%v len(m2)=%d\n", m2, len(m2))
fmt.Printf("m3=%v len(m3)=%d\n", m3, len(m3))
It's on it map How to define ,map It can be defined directly , You can also use make, But the use of make You can't set the size , It's not like slicing ,map It has value when inserting , It's worth it .
2.3.2 Traverse
map Traversal should be here , You know. , Yes ,map Traversal uses range.
for k, v := range m {
fmt.Println(k, v)
}
I won't introduce it here .
2.3.3 operation
Let's try the delete operation :
m["name"] // Get value
delete(m, "name") // Delete
This is not difficult
2.3.4 map Of key
map Use hash table ,key It has to be comparable
except slice,map,function All built-in types can be used as key
Struct Type does not contain the above fields , Have something to do with key
2.3.5 Example
Find the longest string that does not contain duplicate characters :
( After that, I wrote , Ha ha ha )
2.4 Characters and strings
2.4.1 rune
rune Equal to in other languages char, Because it needs to be compatible with Unicode code , So the type is int32, In this way, Chinese can also support .
ss := "hello world Hello , The world "
for i, c := range []rune(ss) {
fmt.Printf("(i=%d c=%c) ", i, c)
}
Running results :
(i=0 c=h) (i=1 c=e) (i=2 c=l) (i=3 c=l) (i=4 c=o) (i=5 c= ) (i=6 c=w) (i=7 c=o) (i=8 c=r) (i=9 c=l) (i=10 c=d) (i=11 c= ) (i=12 c= you ) (i=13 c= good ) (i=14 c=,) (i=15 c= the ) (i=16 c= world )
go Language can print out Chinese directly , If like other languages , Strong conversion []byte It's OK, too .
2.4.2 String manipulation
Use range Traverse pos,rune Yes
Use utf8.RuneCountInString Get the number of characters ( Support Chinese )
Use len Get the byte length ( By byte )
Use []byte Get bytes
2.4.3 Other string operations
Fields,Split,Join
Contains,Index
ToLower,ToUpper
Trim,TrimRight,TrimLeft
边栏推荐
- uwsgi-invalid-request-block-size invalid request block size: 21327 (max 4096)... Skip solution
- ln n, n^k , a^n, n!, The limit problem of n^n
- 中闽在线:以“积分”为纽带 共享线上渠道资源
- Use echart to draw 3D pie chart, dashboard and battery diagram
- How to use dataX to update the data in the downstream Oracle database with the update semantics
- Slurm tutorial
- Large website technology architecture | application server security defense
- What is a forum virtual host? How to choose?
- Interaction between C language and Lua (practice 2)
- ORA-15063: ASM discovered an insufficient number of disks for diskgroup 恢复---惜分飞
猜你喜欢

当程序员编程时被打扰 | 每日趣闻

Golang concise architecture practice

Use echart to draw 3D pie chart, dashboard and battery diagram

Pourquoi golang ne recommande - t - il pas ceci / self / me / this / _ Ça.

Learning signal integrity from scratch -- 7-si analysis and simulation

Researcher of Shangtang intelligent medical team interprets organ image processing under intelligent medical treatment

Overrides vs overloads of methods

Solve the problem that swagger2 displays UI interface but has no content

Golang為什麼不推薦使用this/self/me/that/_this

Digital economy Wang Ning teaches you how to correctly choose short-term investment
随机推荐
What is the difference between TOC and Tob
Importbeandefinitionregistrar registers beans with the container
Network Interview eight part essay of daily knowledge points (TCP, startling group phenomenon, collaborative process)
[sdx62] IPA log fetching instructions
Write the first C application -- Hello, C
QML control types: swipeview, pageindicator
MySQL common SQL
How to deal with too small picture downloaded from xuexin.com
Interaction between C language and Lua (practice 3)
厉害了!淮北两企业获准使用地理标志产品专用标志
System V IPC and POSIX IPC
Disturbed when programmers are programming? Daily anecdotes
通过ip如何免费反查域名?
Web page design and production final assignment report - College Students' online flower shop
Cloud function realizes fuzzy search function
软考2022年下半年考试科目安排
How much does it cost to buy a fixed-term life insurance with an insured amount of 500000 at the age of 42? Is there any product recommendation
【故障诊断】cv2.imwrite无法写入图片,但程序就是不报错
The best time to climb a ladder & sell shares (notes of the runner)
Code example of map and entity class Interoperation