gpt4 book ai didi

go - 如何解释这个 map 语法?

转载 作者:数据小太阳 更新时间:2023-10-29 03:38:33 24 4
gpt4 key购买 nike

我正在研究以下 Go Lang Map 数据结构。我对语法有点困惑 -

//this is fine
countryCapitalMap = make(map[string]string)
/* insert key-value pairs in the map*/
countryCapitalMap["France"] = "Paris"
capital, ok := countryCapitalMap["United States"]

/* print map using keys*/
for country := range countryCapitalMap {
fmt.Println("Capital of", country, "is", countryCapitalMap[country])
}

是不是countryCapitalMap["United States"]从下面这行返回两个返回值

capital, ok := countryCapitalMap["United States"]

或者 countryCapitalMap[country] 从下一行返回单个值

fmt.Println("Capital of", country, "is", countryCapitalMap[country])

我怎样才能破译这个语法?是否基于表达式与哪个语句一起使用

最佳答案

How could I decipher this syntax?

阅读语法的定义。

形式的主要表达

a[x]

表示由 x 索引的 map a 的元素。值 x 称为索引或映射键。

map 上有一种特殊形式的索引表达式。

v, ok = a[x]
v, ok := a[x]
var v, ok = a[x]

产生一个额外的无类型 bool 值。如果映射中存在键 x,则 ok 的值为 true,否则为 false。


The Go Programming Language Specification

Index expressions

A primary expression of the form

a[x]

denotes the element of the array, pointer to array, slice, string or map a indexed by x. The value x is called the index or map key, respectively.

For a of map type M:

  • x's type must be assignable to the key type of M

  • if the map contains an entry with key x, a[x] is the map element with key x and the type of a[x] is the element type of M

  • if the map is nil or does not contain such an entry, a[x] is the zero value for the element type of M

Otherwise a[x] is illegal.

An index expression on a map a of type map[K]V used in an assignment or initialization of the special form

v, ok = a[x]
v, ok := a[x]
var v, ok = a[x]

yields an additional untyped boolean value. The value of ok is true if the key x is present in the map, and false otherwise.


关于go - 如何解释这个 map 语法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54049731/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com