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, 10)
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, 2)
language["php"]["id"] = "1"
language["php"]["desc"] = "php是世界上最美的語言"
language["golang"] = make(map[string]string, 2)
language["golang"]["id"] = "2"
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