0

I have a simple question - can I use single value assignment while method returns 2 values (val and error)?

resp := http.Get("http://www.google.com/")
Vnuuk
  • 6,177
  • 12
  • 40
  • 53
  • Possible duplicate of [Return map like 'ok' in golang on normal functions](http://stackoverflow.com/questions/28487036/return-map-like-ok-in-golang-on-normal-functions) – icza Mar 03 '16 at 08:07

2 Answers2

3

The number of operands on the left side of the assignment must match the number of values returned by the function.

You can use the blank identifier to ignore a return value:

resp, _ := http.Get("http://www.google.com/")

It's bad practice to ignore errors like this.

Charlie Tumahai
  • 113,709
  • 12
  • 249
  • 242
1

From Go language specification :

A tuple assignment assigns the individual elements of a multi-valued operation to a list of variables. There are two forms. In the first, the right hand operand is a single multi-valued expression such as a function call, a channel or map operation, or a type assertion. The number of operands on the left hand side must match the number of values.

For instance, if f is a function returning two values, 
x, y = f() assigns the first value to x and the second to y.

The blank identifier provides a way to ignore right-hand side values in an assignment:

_ = x       // evaluate x but ignore it
x, _ = f()  // evaluate f() but ignore second result value
factotum
  • 900
  • 10
  • 13