Go语言字典(map)的使用
目录
3.字典(map)的使用
3.1 字典的初始化方式1:
package main
import "fmt"
func main() {
var scoreMap = map[string]float32{
"语文": 90.5,
"数学": 88.5,
"英语": 93.5,
}
fmt.Println(scoreMap)
fmt.Printf("%T", scoreMap)
// 控制台输出:map[数学:88.5 英语:93.5 语文:90.5]
// 控制台输出:map[string]float32
}
3.2 字典的初始化方式2:
package main
import "fmt"
func main() {
var scoreMap = map[string]float32{}
scoreMap["语文"] = 90.5
scoreMap["数学"] = 88.5
scoreMap["英语"] = 93.5
fmt.Println(scoreMap)
fmt.Printf("%T", scoreMap)
// 控制台输出:map[数学:88.5 英语:93.5 语文:90.5]
// 控制台输出:map[string]float32
}
3.3 字典的初始化方式3:
package main
import "fmt"
func main() {
var scoreMap = make(map[string]float32, 3)
scoreMap["语文"] = 90.5
scoreMap["数学"] = 88.5
scoreMap["英语"] = 93.5
fmt.Println(scoreMap)
fmt.Printf("%T", scoreMap)
// 控制台输出:map[数学:88.5 英语:93.5 语文:90.5]
// 控制台输出:map[string]float32
}
3.4 字典的遍历1:
package main
import "fmt"
func main() {
var scoreMap = make(map[string]float32, 3)
scoreMap["语文"] = 90.5
scoreMap["数学"] = 88.5
scoreMap["英语"] = 93.5
for key, item := range scoreMap {
fmt.Print("\""+key+"\" = ", item, " ")
}
// 控制台输出:"语文" = 90.5 "数学" = 88.5 "英语" = 93.5
}
3.5 字典的遍历2:
package main
import "fmt"
func main() {
var scoreMap = make(map[string]float32, 3)
scoreMap["语文"] = 90.5
scoreMap["数学"] = 88.5
scoreMap["英语"] = 93.5
for key := range scoreMap {
fmt.Print("\""+key+"\" = ", scoreMap[key], " ")
}
// 控制台输出:"语文" = 90.5 "数学" = 88.5 "英语" = 93.5
}
3.6 判断字典中有无某个key
package main
import "fmt"
func main() {
var scoreMap = make(map[string]float32, 3)
scoreMap["语文"] = 90.5
scoreMap["数学"] = 88.5
scoreMap["英语"] = 93.5
score, exist := scoreMap["物理"]
if exist {
fmt.Println("物理成绩存在,物理成绩 = ", score)
} else {
fmt.Println("物理成绩不存在!")
}
// 控制台输出:物理成绩不存在!
}
3.7 删除字典中的某个键值对
package main
import "fmt"
func main() {
var scoreMap = make(map[string]float32, 3)
scoreMap["语文"] = 90.5
scoreMap["数学"] = 88.5
scoreMap["英语"] = 93.5
scoreMap["物理"] = 85.5
fmt.Println(scoreMap)
// 控制台输出:map[数学:88.5 物理:85.5 英语:93.5 语文:90.5]
delete(scoreMap, "物理")
fmt.Println(scoreMap)
// 控制台输出:map[数学:88.5 英语:93.5 语文:90.5]
}