5.map

Declare, initialize and iterate

// Sample program to show how to declare, initialize and iterate
// over a map. Shows how iterating over a map is random.

package main

import "fmt"

// user defines a user in the program.
type user struct {
	name    string
	surname string
}

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["Roy"] = user{"Rob", "Roy"}
	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)
	}
	/*

	   Mouse {Mickey Mouse}
	   Jackson {Michael Jackson}
	   Roy {Rob Roy}
	   Ford {Henry Ford}

	   Roy
	   Ford
	   Mouse
	   Jackson
	*/
}

Map literals and delete

// Sample program to show how to declare and initialize a map
// using a map literal and delete a key.
//示例程序演示如何声明和初始化地图。
//使用地图文字并删除一个键。

package main

import "fmt"

// user defines a user in the program
type user struct {
	name    string
	surname string
}

func main() {

	// Declare and initialize the map with values.
	users := map[string]user{
		"Roy":     {"Rob", "Roy"},
		"Ford":    {"Henry", "Ford"},
		"Mouse":   {"Mickey", "Mouse"},
		"Jackson": {"Michael", "Jackson"},
	}

	//	iterate over the map.
	for k, v := range users {
		fmt.Println(k, v)
	}

	// Delete the Roy key.
	delete(users, "Roy")

	// Find the Roy key.
	u, found := users["Roy"]

	// Display the value and found flag.
	fmt.Println("Roy", found, u)

	/*
		Ford {Henry Ford}
		Mouse {Mickey Mouse}
		Jackson {Michael Jackson}
		Roy {Rob Roy}
		Roy false { }

	*/

}

Map key restrictions key类型

package main

import "fmt"

// user defines a user in the program.
type user struct {
	name    string
	surname string
}

// users define a set of users.
type users []user

func main() {
	// Declare and make a map uses a slice of users as the key.
	u := make(map[users]int) // map key type must not be a func ,map os slice

	// ./example3.go:22: invalid map key type users

	// Iterate over the map.

	for key, value := range u {
		fmt.Println(key, value)
	}
}

原文地址:https://www.cnblogs.com/zrdpy/p/8586343.html