1、map的基本用法
package main;
import "fmt";
func main() {
var map1 map[string]int;
map2 := make(map[string]int);
var map3 map[string]int;
map1 = map[string]int{"key1": 1, "key2": 2};
map3 = map1;
map2["k1"] = 11;
fmt.Printf("map1: %d\n", map1["key1"]);
fmt.Printf("map2: %d\n", map2["k1"]);
fmt.Printf("map3: %d\n", map3["key1"]);
// map3直接指向map1, 所以会修改原来的map1
map3["key1"] = 111;
fmt.Printf("map1: %d\n", map1["key1"]);
fmt.Printf("map3: %d\n", map3["key1"]);
}
2、判断key不存在,还是key的value是空
package main;
import "fmt";
func main() {
map1 := map[string]string{"key1": "value1", "key2": "value1", "key3": "value3"};
// key1存在
_, b1 := map1["key1"];
fmt.Printf("b1=%t\n", b1);
// 删除key1
delete(map1, "key1");
// key1不存在
_, b2 := map1["key1"];
fmt.Printf("b2=%t\n", b2);
}
3、遍历和排序
package main;
import "fmt";
import "sort";
func main() {
map1 := map[string]string{"key1": "value1", "key2": "value2", "key3": "value3"};
var keys []string;
// 注意: go的map对key和value是无序的
// k和v
for k, v := range map1 {
fmt.Printf("k=%s, v=%s\n", k, v);
}
// 只取key
for k := range map1 {
keys = append(keys, k);
fmt.Printf("origin map sort, k=%s\n", k);
}
// 只取key
for _, v := range map1 {
fmt.Printf("v=%s\n", v);
}
// 如果一定要排序, 需要将key放到切片中再排序
sort.Strings(keys);
for _, k := range keys {
fmt.Printf("after sort k=%s\n", k);
}
}
网友评论