Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get only a specific value out of a function call with multiple return values?

Tags:

go

Given swap, a function that returns multiple values, and supposing it's part of some API I can't modify:

package main

import "fmt"

func swap(x, y string) (string, string) {
    return y, x
}

func main() {
    a, b := swap("hello", "world")
    fmt.Println(a, b)
}

Is it possible to use swap function and get only the first returned value, discarding the second one? I tried this:

func main() {
    a, b := swap("hello", "world")
    fmt.Println(a)
}

ERROR: prog.go:10: b declared and not used [process exited with non-zero status]

And this is not possible too:

a := swap("hello", "world")

ERROR: prog.go:10: multiple-value swap() in single-value context

How to deal with functions that return multiple values when I don't need all the returned parts?


Code is based on "A tour of go - lesson 9"

like image 605
marcio Avatar asked May 19 '14 10:05

marcio


1 Answers

Use the blank identifier _:

a, _ := swap("hello", "world")

Everything assigned to the blank identifier is silently discarded without a warning being raised. You can also use the blank identifier to add padding to structures:

struct {
    a byte
    b byte
    c byte
    _ byte // padding
}

Another usage of the blank identifier is to discard return values when initializing global variables:

var foo, _ = foo.NewFoo() // ignore error returned by NewFoo()

And when only one value of a range is required:

for _, v := range mySlice { }
like image 105
fuz Avatar answered Oct 10 '22 18:10

fuz