Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does range or map return?

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 {}
}

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?

like image 607
Jaynti Kanani Avatar asked Nov 02 '13 10:11

Jaynti Kanani


1 Answers

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

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.

and

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)

like image 70
ANisus Avatar answered Oct 16 '22 23:10

ANisus