前往:范围或地图返回什么? [英] Go: What does range or map return?

查看:73
本文介绍了前往:范围或地图返回什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Go具有非常整洁的多个返回值范例.但是,看来v, ok := map[key]v, k := range 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, ok := m["One"]v := m["One"]-这两个表达式都可以正常工作. 为什么会有这种不同的行为?

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?

推荐答案

从内置map中获取内容,在地图,数组或切片上使用range,并且type assertions允许一个或两个变量.用户定义的函数和方法不是这种情况.如果一个函数声明了两个返回值,则必须告诉他们如何处理这两个返回值,或者忽略这两个值:

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):

map [K] V类型的map a上的索引表达式可用于特殊形式的赋值或初始化

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,确定= a [x]
v,好的:= a [x]
var v,ok = 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):

对于每次迭代,迭代值产生如下:

For each iteration, iteration values are produced as follows:

范围表达式: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:

对于接口类型为T且类型为T的表达式x,主要表达式
x.(T)
断言x不是nil,并且存储在x中的值是T类型.

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.

如果在类型的赋值或初始化中使用类型断言
v,确定= x.(T)
v,好的:= x.(T)
var v,ok = x.(T)
声明的结果是一对类型为(T,bool)的值

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)

这篇关于前往:范围或地图返回什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆