jameshfisher
jameshfisher

Reputation: 36397

How do I declare multiple variables instantiated by a function call returning multiple values in Go?

Let's say I have a function:

func foo() (bool, string) { ... }

And then I wish to declare two variables b and s, initialized with values returned by the function call foo(). I'm aware I can do this using the "shorthand" syntax which omits type annotations:

b, s := foo();

However, I do not wish to use this shorthand syntax. I wish to use the var syntax with a variable name and expected type. I have tried this:

var b bool, s string = foo();

However, this gives me a syntax error. What is the correct way to do this?

Upvotes: 0

Views: 64

Answers (2)

Rob Napier
Rob Napier

Reputation: 299265

In most cases, the correct way to do this is to use the shorthand syntax. That's what it's for.

If you don't want to use the shorthand syntax, then you can use var syntax:

var b bool
var s string
b, s = foo()

or

var (
    b bool
    s string
)
b, s = foo()

There is no "shorthand var" syntax.

Upvotes: 6

Ainar-G
Ainar-G

Reputation: 36189

You can't do that. The Go Spec defines a variable declaration grammar as follows:

VarDecl     = "var" ( VarSpec | "(" { VarSpec ";" } ")" ) .
VarSpec     = IdentifierList ( Type [ "=" ExpressionList ] | "=" ExpressionList ) .

Variables in the IdentifierList can only have either one Type for all, or none. The best you can do is either

var b, s = foo()

or, if you want them at the top level of your package,

var (
    b bool
    s string
)

func init() {
    b, s = foo()
}

Upvotes: 2

Related Questions