声明一个map var my map[int]int 这个map 是nil ,值为 map[],长度为0 ,hash[key]=value 赋值报错,单允许访问
声明map make方式 var my make(map[T]T,num) ,num为初始map长度,默认为0
map的key 不能是function,slice,map,可以是bool,数字,string,指针,channer,interface,struct,array in short 可以用==判断 As mentioned earlier, map keys may be of any type that is comparable. The language spec defines this precisely, but in short, comparable types are boolean, numeric, string, pointer, channel, and interface types, and structs or arrays that contain only those types. Notably absent from the list are slices, maps, and functions; these types cannot be compared using ==, and may not be used as map keys.
func main() {
// Declare and make a map that stores values
// of type user with a key of type string.
users := make(map[string]user)
// Add key/value pairs to the map.
users["Rob"] = user{"Roy", "Rob"}
users["Ford"] = user{"Henry", "Ford"}
users["Mouse"] = user{"Mickey", "Mouse"}
users["Jackson"] = user{"Michael", "Jackson"}
// Iterate over the map.
for key, value := range users {
fmt.Println(key, value)
}
fmt.Println()
// Iterate over the map and notice the
// results are different.
for key := range users {
fmt.Println(key)
}
}
// Sample program to show how to declare and initialize a map
// using a map literal.
type user struct {
name string
email string
}
// main is the entry point for the application.
func main() {
// Declare and initialize the map with values.
users := map[string]user{
"Rob": user{"Roy", "Rob"},
"Ford": user{"Henry", "Ford"},
"Mouse": user{"Mickey", "Mouse"},
"Jackson": user{"Michael", "Jackson"},
}
// Iterate over the map.
for key, value := range users {
fmt.Println(key, value)
}
}
Sample program to show how to compose maps of maps.
// Data defines a key/value store.
type Data map[string]string
Sample program to show how to compose maps of maps.
// main is the entry point for the application.
func main() {
// Declare and make a map of Data type values.
users := make(map[string]Data)
// Initialize some data into our map of maps.
users["clients"] = Data{"123": "Henry", "654": "Joan"}
users["admins"] = Data{"398": "Bill", "076": "Steve"}
// Iterate over the map of maps.
for key, data := range users {
fmt.Println(key)
for key, value := range data {
fmt.Println("\t", key, value)
}
}
}
声明一个map var my map[int]int 这个map 是nil ,值为map[],长度为0 ,hash[key]=value 赋值报错,单允许访问 声明map make方式 var my make(map[T]T,num) ,num为初始map长度,默认为0 map的key 不能是function,slice,map,可以是bool,数字,string,指针,channer,interface,struct,array in short 可以用==判断 As men...