简体   繁体   中英

Return 1 value to the function with multiple return values in golang

I want to return just 1 value to the function with multiple return values. I tried this:

func myFunc() (int, int){
    return _, 3
}

But it didn't work and raised this error: cannot use _ as value

I already know that It's possible to receive one of the returned values.

Is there any way to return just 1 value?

Use the zero value for the other return parameters:

func myFunc() (int, int){
    return 0, 3
}

If you use named result parameters, you may also do:

func myFunc() (x, y int){
    y = 3
    return
}

In this case x will also be the zero value of its type, 0 in case of int .

You could also write a helper function which adds a dummy return value, eg:

func myFunc() (int, int) {
    return extend(3)
}

func extend(i int) (int, int) {
    return 0, i
}

But personally I don't think it's worth it. Just return the zero value for "unused" return parameters.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM