Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can you declare multiple variables at once in Go?

Is it possible to declare multiple variables at once using Golang?

For example in Python you can type this:

a = b = c = 80 

and all values will be 80.

like image 530
Kevin Burke Avatar asked Jan 12 '14 05:01

Kevin Burke


People also ask

Can you initialize multiple variables at once?

Example - Declaring multiple variables in a statementIf your variables are the same type, you can define multiple variables in one declaration statement. For example: int age, reach; In this example, two variables called age and reach would be defined as integers.

Can you declare multiple variables?

But there are actually shorter ways to declare multiple variables using JavaScript. First, you can use only one variable keyword (var, let, or const) and declare the variable names and values separated by commas.

Can you declared multiple types of variables in single declaration in Go?

You can use the same syntax in function parameter declarations: func foo(a, b string) { // takes two string parameters a and b ... } Then comes the short-hand syntax for declaring and assigning a variable at the same time.


2 Answers

Yes, you can:

var a, b, c string a = "foo" fmt.Println(a) 

You can do something sort of similar for inline assignment, but not quite as convenient:

a, b, c := 80, 80, 80 
like image 124
Kevin Burke Avatar answered Sep 29 '22 15:09

Kevin Burke


In terms of language specification, this is because the variables are defined with:

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

(From "Variable declaration")

A list of identifiers for one type, assigned to one expression or ExpressionList.

const a, b, c = 3, 4, "foo"  // a = 3, b = 4, c = "foo", untyped integer and string constants const u, v float32 = 0, 3    // u = 0.0, v = 3.0 
like image 23
VonC Avatar answered Sep 29 '22 15:09

VonC