首页 > 其他 > 详细

5.map

时间:2018-03-16 23:34:31      阅读:385      评论:0      收藏:0      [点我收藏+]

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)
    }
}

5.map

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

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!