funcmain() { a := make(map[string]string) a["name"] = "Payne" a["sex"] = "male" a["year"] = "20" fmt.Println("a:", a) // a: map[name:Payne sex:male year:20] fmt.Println("a['sex']:", a["sex"]) // a['sex']: male fmt.Printf("Type of a:%T\n", a) // Type of a:map[string]string
b := map[string]string{ "Name": "Tim", "Sex": "male", "Year": "20", } fmt.Println("b:", b) // b: map[Name:Tim Sex:male Year:20] fmt.Println("b['sex']:", b["Sex"]) // b['sex']: male fmt.Printf("Type of b:%T", b) // Type of b:map[string]string }
// 遍历 d := map[string]string{ "name1": "Tom", "name2": "Tim", "name3": "Payne", "name4": "John", } // 只遍历key for d := range d { fmt.Print(d + ",") // name1,name2,name3,name4, } fmt.Printf("\n") // 只遍历value for _, v := range d { fmt.Print(v + ",") // Tom,Tim,Payne,John, } fmt.Printf("\n") // 遍历key value for k, v := range d { fmt.Print(k, ":", v, " ") // name2:Tim name3:Payne name4:John name1:Tom }