-1

Recently, I studied that Golang can return multiple result for a function. So I write a function:

func store(x, y int) (int, int) {
    return x + y, x - y
}

After this I write the following code:

func main() {
    a, b := store(6, 4)
    fmt.Println(a, b)
} 

And, the result is:

10 2

This is working fine.

But if I want to print only a, then how can I do this?

func main() {
    a, b := store(6, 4)
    fmt.Println(a)
}

Result:

tmp/sandbox683412938/main.go:12:19: b declared and not used

Also, why I can't write:

func main() {
    a := store(6, 4) // ???
    fmt.Println(a)
}

Please, guide me.

Harry
  • 136
  • 4
  • 11
  • 1
    See related / possible duplicates: [Return map like 'ok' in Golang on normal functions](https://stackoverflow.com/questions/28487036/return-map-like-ok-in-golang-on-normal-functions/28487270#28487270); and [Go: multiple value in single-value context](https://stackoverflow.com/questions/28227095/go-multiple-value-in-single-value-context/28233172#28233172). – icza Nov 16 '17 at 07:46

1 Answers1

9

You can use underscore placeholder (blank identifier) like this:

a, _ := store(6, 4)
fmt.Println(a)

Output:

10

Here's the complete example:

package main

import (
    "fmt"
)

func store(x, y int) (int, int) {
    return x + y, x - y
}

func main() {
    a, _ := store(6, 4)
    fmt.Println(a)
}

Live example: https://play.golang.org/p/Z366BhtRA0

Azeem
  • 11,148
  • 4
  • 27
  • 40