当前位置:网站首页>Section 2 map and structure in Chapter 6
Section 2 map and structure in Chapter 6
2022-04-23 03:27:00 【Python code doctor】
Map
summary
Go In language map( mapping 、 Dictionaries ) It's a built-in data structure , It's a disorder Of key—value For the collection of , For example, ID card number is used as a unique key to identify a person's information .
info := map[int]string{
110: "mark",
111: "yoyo",
112: "lili",
}
:
map The format is :
map[KeyType]valueType
In a map All the keys in the are only Of , And it has to be support == and != The type of operator , section 、 Functions and structure types that contain slices because of their referential semantics , Can't be a key to a map , Using these types can cause compilation errors :
dict := map[ []string ]int{} //err, invalid map key type []string
map Values can be any type , There is no limit to .map All keys in must have the same data type , Value must also be how , But the data types of keys and values can be different .
Be careful :map yes disorder Of , We can't decide the return order , therefore , The order of printing results may be different each time .
Create and initialize
map The creation of
var m1 map[int]string // Just a statement map, Not initialized , This is empty (nil)map
fmt.Println(m1 == nil) //true
//m1[1] = "mike" //err, panic: assignment to entry in nil map
// m2, m3 The creation method of is equivalent
m2 := map[int]string{
}
m3 := mmake(map[int]string)
fmt.Printlnn(m2, m3) //map[] map[]
m4 := make(mmap[int]string, 10) // The second parameter specifies the capacity
fmt.Println(m4) //map[]
initialization
//1、 Definitions are initialized at the same time
var m1 map[int]string = map[int]string{
1: "mike", 2: "yoyo"}
fmt.Println(m1) //map[1:mike 2:yoyo]
//2、 Automatic derivation type :=
m2 := map[int]string{
1: "mike", 2: "yoyo"}
fmt.Println(m2)
Common operations
assignment
m1 := map[int]string{
1: "mike", 2: "yoyo"}
m1[1] = "xxx" // modify
m1[3] = "lily" // Additional ,go The bottom layer will automatically be map Allocate space
fmt.Println(m1) //map[1:xxx 2:yoyo 3: lily]
m2 := make(map[int]string, 10) // establish map
m2[0] = "aaa"
m2[1] = "bbb"
fmt.Println(m2) //map[0:aaa 1:bbb]
fmt.Println(m2[0], m2[1]) //aaa bbb
Traverse
m1 := map[int]string{
1: "mike", 2: "yoyo"}
// Iterate through 1, The first return value is key, The second return value is value
for k,v := range m1 {
fmt.Printf("%d ----> %s\n", k, v)
//1 ----> mike
//2 ----> yoyo
}
// Iterate through 2, The first return value is key, The second return value is value( Omission )
for k := range m1 {
fmt.Printf("%d ----> %s\n", k, m1[k])
//1 ----> mike
//2 ----> yoyo
}
// Judge a certain key The corresponding value Whether there is , The first return value is value( If it exists )
value, ok := m1[1]
fmt.Println("value = ", value, ",ok = ", ok) //value = mike, ok = true
value2, ok2 := m1[3]
fmt.Println("value2 = ",value2, ", ok2 = ", ok2) //value2 = , ok2 = false
Delete
m1 := map[int]string{
1: "mike", 2: "yoyo", 3: "lily"}
// Iterate through 1, The first return value is key, The second return value is value
for k,v := range m1 {
fmt.Printf("%d ----> %s\n", k, v)
//1 ----> mike
//2 ----> yoyo
//3 ----> lily
}
delete(m1, 2) // Delete key The value is 3 Of map
for k, v := range m1 {
fmt.Printf("%d ----> %s\n", k, v)
//1 ----> mike
//3 ----> lily
}
map Do function parameters
Passing a map between functions does not make a copy of that map , Not value passing , It's a reference to pass :
func DeleteMap(m map[int]string,key int) {
delete(m, key) // Delete key The value is 3 Of map
for k, v := range m {
fmt.Printf("len(m)=%d, %d ----> %s\n", len(m), k, v)
//len(m)=2, 1 ----> mike
//len(m)=2, 3 ----> lily
}
}
func main() {
m := map[int]strinng{
1: "mike", 2: "yoyo", 3: "lily"}
DeleteMap(m,2) // Delete key The value is 3 Of map
for k, v := range m {
fmt.Printf(""len(m)=%d, %d ----> %s\n", len(m), k, v)
//len(m)=2, 1 ----> mike
//len(m)=2, 3 ----> lily
}
}
Structure
Type of structure
Sometimes we need to combine different types of data into an organic whole , Such as : A student has a student number / full name / Gender / Age / Address and other properties . Obviously, it is tedious to define the above variables alone , Data is not easy to manage .
A structure is an aggregate data type , It is a data set composed of a series of data of the same type or different types . Each data is called a member of the structure .
Structure initialization
//1、 Print members
var s1 Student = Student{
1, "mark", 'm', 18, "sz"}
// result :id = 1, name = mark, sex = m, age =18, addr =sz
//2、 Member variable assignment
var s2 Student
s2.id = 2
s2.name = "yoyo"
s2.sex = 'f'
s2.age = 16
s2.addr = "guangzhou"
fmt.Println(s2) //{2 yoyo 102 16 guangzhou}
Structure comparison
If all members of a structure are comparable , So the structure can also be compared , In that case, two structures can be used == or != Operator to compare , But does not support > or < .
func := Student{
s1 := Student{
1, "mike", 'm', 18, "sz"}
s2 := Student{
1, "mike", 'm', 18, "sz"}
fmt.Println(fmt.Println("s1 == s2", s1 == s2) //s1 == s2 true
fmt.Println("s1 != s2", s1 != s2) //s1 != s2 false
}
Array of structs
type Student struct {
id int
name string
score int
}
func main() {
// Array of structs
var arr []Student = []Student{
Student{
1, " Li Bai ", 100},
Student{
2, " Wang wei ", 100},
Student{
3, " Du Fu ", 100},}
fmt.Println(arr)
// Print structure information circularly
for i := 0; i < len(arr); i++ {
fmt.Println(arr[i])
}
}
Structure as function parameter
type Hero struct {
name string
age int
power int
}
// Structure as function parameter
func test18(h Hero) {
h.power = 120
fmt.Println(h)
}
func main() {
// Structural variable
h := Hero{
" Iron man ", 30, 100}
// Value passed
test18(h)
fmt.Println(h)
}
版权声明
本文为[Python code doctor]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/04/202204220619244268.html
边栏推荐
- 2021-08-11
- Utgard connection opcserver reported an error caused by: org jinterop. dcom. common. JIRuntimeException: Access is denied. [0x800
- Unity knowledge points (common core classes)
- Problem B: small challenge
- socket編程 send()與 recv()函數詳解
- Idempotency practice operation, explaining idempotency based on business
- 月薪10k-20k都无法回答的事务问题,你会吗?
- MySQL之explain关键字详解
- The query type of MySQL is very inefficient.
- Query stored procedures in PostgreSQL
猜你喜欢
Supersocket is Use in net5 - concept
可以接收多種數據類型參數——可變參數
Supersocket is Use in net5 - startup
Chapter 9 of C language programming (fifth edition of Tan Haoqiang) analysis and answer of exercises for users to establish their own data types
General test technology [II] test method
MySQL keyword group_ Concat, combined connection query
Visual programming -- how to customize the mouse cursor
打卡:4.22 C语言篇 -(1)初识C语言 - (11)指针
2022 团体程序设计天梯赛 模拟赛 L2-3 浪漫侧影 (25 分)
IOTOS物联中台对接海康安防平台(iSecure Center)门禁系统
随机推荐
Web Course Design - his system
Idea view history [file history and project history]
Punch in: 4.23 C language chapter - (1) first knowledge of C language - (12) structure
Flink customizes the application of sink side sinkfunction
Supersocket is Use in net5 - concept
2022 团体程序设计天梯赛 模拟赛 1-8 均是素数 (20 分)
Seminar playback video: how to improve Jenkins' ability to become a real Devops platform
Codeforces round 784 (Div. 4) (AK CF (XD) for the first time)
Node configuration environment CMD does not take effect
WinForm allows the form form to switch between the front and active states
Cefsharp stores cookies and reads cookies
Course design of Database Principle -- material distribution management system
Codeforces Round #784 (Div. 4)題解 (第一次AK cf (XD
C-11 problem h: treasure chest 2
Iotos IOT middle platform is connected to the access control system of isecure center
Téléchargement en vrac de fichiers - téléchargement après compression
月薪10k-20k都无法回答的事务问题,你会吗?
POI create and export Excel based on data
AWS from entry to actual combat: creating accounts
Docker拉取mysql并连接