Golang中map的三种声明方式和简单实现增删改查

时间:2023-03-08 17:11:37
package main

import (
"fmt"
) func main() {
test3 := map[string]string{
"one": "php",
"two": "golang",
"three": "java",
}
no_exsits, ok := test3["three"]
fmt.Println(no_exsits, ok)
if no_exsits, ok := test3["four"]; ok {
fmt.Println(no_exsits)
} else {
fmt.Println("KEY not exist")
} } //java true
//KEY not exist

map就相当于php语言中的关联数组

//代码
package main
import (
"fmt"
) func main() {
//第一种声明
var test1 map[string]string
//在使用map前,需要先make,make的作用就是给map分配数据空间
test1 = make(map[string]string, )
test1["one"] = "php"
test1["two"] = "golang"
test1["three"] = "java"
fmt.Println(test1) //map[two:golang three:java one:php] //第二种声明
test2 := make(map[string]string)
test2["one"] = "php"
test2["two"] = "golang"
test2["three"] = "java"
fmt.Println(test2) //map[one:php two:golang three:java] //第三种声明
test3 := map[string]string{
"one" : "php",
"two" : "golang",
"three" : "java",
}
fmt.Println(test3) //map[one:php two:golang three:java] language := make(map[string]map[string]string)
language["php"] = make(map[string]string, )
language["php"]["id"] = ""
language["php"]["desc"] = "php是世界上最美的语言"
language["golang"] = make(map[string]string, )
language["golang"]["id"] = ""
language["golang"]["desc"] = "golang抗并发非常good" fmt.Println(language) //map[php:map[id:1 desc:php是世界上最美的语言] golang:map[id:2 desc:golang抗并发非常good]] //增删改查
// val, key := language["php"] //查找是否有php这个子元素
// if key {
// fmt.Printf("%v", val)
// } else {
// fmt.Printf("no");
// } //language["php"]["id"] = "3" //修改了php子元素的id值
//language["php"]["nickname"] = "啪啪啪" //增加php元素里的nickname值
//delete(language, "php") //删除了php子元素
fmt.Println(language)
}

补充:判断一个不存在的key

package main

import (
"fmt"
) func main() {
test3 := map[string]string{
"one": "php",
"two": "golang",
"three": "java",
}
no_exsits, ok := test3["three"]
fmt.Println(no_exsits, ok)
if no_exsits, ok := test3["four"]; ok {
fmt.Println(no_exsits)
} else {
fmt.Println("KEY not exist")
} }
//java true
//KEY not exist