0

Is there a way in go to assign two variables to a function that returns two values when you have one variable declared and the other not.

For example:

var host string
if host, err := func(); err != nil {}

In the above code, host is declared but err isn't. I want a clean way to do this other than declaring err

Keeto
  • 4,074
  • 9
  • 35
  • 58
  • Pretty sure it does that automatically. := if there is a new variable, = if both exist. – Puzzle84 Aug 18 '16 at 22:55
  • If the second statement is an if/for statement. Will the declared variable "host" hold the value returned by func()? – Keeto Aug 18 '16 at 23:00
  • Short answer is what you're asking for isn't possible. You have to also declare `err`. – Endophage Aug 19 '16 at 00:38
  • @Keeto see: http://stackoverflow.com/questions/36553134/in-golang-where-can-we-use-variable-scoping-and-shadowing-and-how –  Aug 19 '16 at 07:16

2 Answers2

7

In your example you simply shouldn't be declaring host. There is no way to do partial assignment like that... Either your using := which is short hand for declaration and assignment or you using = and you're doing assignment only. I personally very rarely write the word var in Go.

To be clear, if you have one variable that has already been declared with one or more that have not, you're allowed to use := to assign to it, but the inverse is not true. Meaning you cannot use = if one or more of the left hand side values haven't been declared already.

evanmcdonnal
  • 46,131
  • 16
  • 104
  • 115
  • If the second statement is an if/for statement. Will the declared variable "host" hold the value returned by func()? – Keeto Aug 18 '16 at 23:00
  • @Keeto it will, however when you do that `host` will only be available in the scope of the `if`. Here's an example on play; https://play.golang.org/p/3ONeB2D6kH As you can see host isn't in scope outside the if. – evanmcdonnal Aug 18 '16 at 23:09
2

When you use := in an if like that, you will always get new variables declared in the scope of the if. Following the if, the value of host will be the same as it was before. If you want to do this, you need to declare both host and err before the if (and don't use := in the if).

Andy Schweig
  • 6,597
  • 2
  • 16
  • 22