问题描述
Go具有非常整齐的多个返回值范例。但是看起来 v,好的:= map [key]
和 v,k:=范围m
具有相同的符号。这是一个简单的示例:
Go has very neat multiple return values paradigm. But It looks like v, ok := map[key]
and v, k := range m
use different mechanism with same notation. Here is a simple example:
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,确定:= m [一个]
和 v:= m [一个]
-这两个表达式都可以正常工作。
为什么会有不同的行为?
In above example, k := f2()
gives error as f2
returns two values, whereas v, ok := m["One"]
and v := m["One"]
- both expressions work without any error.Why is that different behavior?
推荐答案
从内置的映射中提取
,在地图,数组或切片上使用 range
,还使用 type断言
允许一个或两个变量。用户定义的函数和方法不是这种情况。如果一个函数声明了两个返回值,则必须告诉它们如何处理这两个值,或者忽略这两个值:
A fetch from the built in map
, using range
on a map, array or slice, and also type assertions
allows for one or two variables. This is not the case for user defined functions and methods. If a function declares two return values, you must tell what to do with both of them, or ignore both:
k, _ := f2() // Specify what to do with each returned value
f2() // Ignoring both
为什么?因为规范说的是这样的:
Why? Because the specification says it is so:
Map (indexed expressions):
v,确定= a [x]
v,确定:= a [x ]
var v,确定= a [x]
v, ok = a[x]
v, ok := a[x]
var v, ok = a[x]
其中索引表达式的结果是一对类型为(V,bool )。以这种形式,如果键x存在于映射中,则ok的值为true,否则为false。 v的值是单结果形式的值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):
范围表达式:m map [K] V
第一个值:键k K
第二个值(如果存在第二个变量):m [k] V
Range expression: m map[K]V
1st value: key k K
2nd value (if 2nd variable is present): m[k] V
Type assertion:
和
这篇关于范围或地图返回什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!