dictionary - range 或 map 返回什么?

标签 dictionary go range

Go 有非常简洁的多返回值范式。但看起来 v, ok := map[key]v, k := range m 使用不同的机制和相同的符号。这是一个简单的例子:

func f2() (k, v string) {
    return "Hello", "World"
}

func main(){
    k := f2() // Doesn't work : multiple-value f2() in single-value context

    m := map[string]int{"One": 1}

    // It works
    v, ok := m["One"]

    // How it all work?
    v := m["One"]
    for k := range m {}
}

在上面的示例中,k := f2() 给出错误,因为 f2 返回两个值,而 v, ok := m["One"] v := m["One"] - 这两个表达式都没有任何错误。 为什么会有这种不同的行为?

最佳答案

从内置的 map 获取,在 map、array 或 slice 上使用 range,以及 type assertions 允许一个 < em>或两个变量。用户定义的函数和方法不是这种情况。如果一个函数声明了两个返回值,你必须告诉你如何处理它们,或者忽略它们:

k, _ := f2() // Specify what to do with each returned value
f2() // Ignoring both

为什么?因为规范是这样说的:

Map (indexed expressions):

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

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

where the result of the index expression is a pair of values with types (V, bool). In this form, the value of ok is true if the key x is present in the map, and false otherwise. The value of v is the value a[x] as in the single-result form.

Range (for statement):

For each iteration, iteration values are produced as follows:

Range expression: m map[K]V
1st value: key k K
2nd value (if 2nd variable is present): m[k] V

Type assertion:

For an expression x of interface type and a type T, the primary expression
x.(T)
asserts that x is not nil and that the value stored in x is of type T.

If a type assertion is used in an assignment or initialization of the form
v, ok = x.(T)
v, ok := x.(T)
var v, ok = x.(T)
the result of the assertion is a pair of values with types (T, bool)

关于dictionary - range 或 map 返回什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19741174/

相关文章:

dictionary - 如何将 POST 正文绑定(bind)到 map ?

go - Setter 不在模型中工作

memory-management - 我是否需要将 map 设置为 nil 才能对其进行垃圾回收?

c - 在 K&R 2-1 中解释这段代码

arrays - 当数组分配给 Sub 内的范围时,VBA 在结束语句或重置时崩溃

python - 这是扁平化字典列表的可接受方法吗?

linux - Bash hashmap 使用引号作为键

loops - 使用 Google Script 循环浏览 Google Sheets 中某个范围内的单元格

python - 如果行中的指定值匹配条件,则从 CSV 返回行

go - 在 Go 网络应用程序中加载 key 的最佳实践是什么?