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
为什么?因为规范是这样说的:
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.
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
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/