mapkeymapkey
map

map 的语法

var map_name map[KeyType]ValueType
KeyTypeValueTypemap
package main
import "fmt"
func main() {
    map_1 := map[string]string{
        "Jenna": "Sthapit"
    }
    for k, v := range map_1 {
        fmt.Printf("Key:%v\nValue: %s\n", k, v)
    }
}

输出:

Key:Jenna
Value: Sthapit
map_1map_1SthapitJenna
map

Go map 中检查是否包含某键

first_value, second_value := map_name[key_name]
first_valuesecond_valuefirst_valuekeymap_namekey_namefirst_valuesecond_valuemapkey_nametruefirst_valuesecond_valuemap_namekey_name
package main
import "fmt"
func main() {
    map_name := map[int]string{
        0: "Alok",
        1: "Reman",
        2: "Riken",
        3: "Rudra",
    }
    _, second_value_1 := map_name[1]
    fmt.Printf("second_value for 1: %t\n", second_value_1)
    _, second_value_9 := map_name[9]
    fmt.Printf("second_value for 9: %t\n", second_value_9)
}

输出:

second_value for 1: true
second_value for 9: false
0second_valuetruemap_name0map_namesecond_valuefalse
package main
import "fmt"
func main() {
    map_name := map[string]string{
        "Giri":     "Alok",
        "Nembang":  "Reman",
        "Maharjan": "Riken",
        "Jha":      "Rudra",
    }
    if first_value, second_value := map_name["Giri"]; second_value {
        fmt.Printf("Giri is present in map. Value is: %s\n", first_value)
    } else {
        fmt.Printf("Giri is not present in map.\n")
    }
    if first_value, second_value := map_name["Sthapit"]; second_value {
        fmt.Printf("Sthapit is present in map. Value is: %s\n", first_value)
    } else {
        fmt.Printf("Sthapit is not present in map. \n")
    }
}

输出:

Giri is present in map. Value is: Alok
Sthapit is not present in map.
ifGiriSthapitmap_name
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布,任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站。本站所有源码与软件均为原作者提供,仅供学习和研究使用。如您对本站的相关版权有任何异议,或者认为侵犯了您的合法权益,请及时通知我们处理。