map 的下标语法可返回两个值(如 age, ok := ages["bob"]),第二个布尔值 ok 用于判断元素是否存在,常用于条件判断。
实现集合(Set)
Go 语言没有内置 Set 类型,但可用 map[string]bool 替代。通过键的唯一性去重,例如 dedup 程序通过 seen[line] = true 标记已存在的行。
funcmain(){
seen :=make(map[string]bool)// a set of strings
input := bufio.NewScanner(os.Stdin)for input.Scan(){
line := input.Text()if!seen[line]{
seen[line]=true
fmt.Println(line)}}if err := input.Err(); err !=nil{
fmt.Fprintf(os.Stderr,"dedup: %v\n", err)
os.Exit(1)}}