Go Multiple Variable Declaration
Go lets you put several variable declarations on one line.
Note: If you write a type in that declaration, it applies to every variable, so they must all be of one type.
Leave the type out, and the variables on that line can have different types. The examples below show both cases.
Example
Here, four variables of type int are declared on one line:
Prompt
Declare multiple int variables on the same line and print each one.
Output: Go program and captured output
main.go
package main
import ("fmt")
func main() {
var a, b, c, d int = 1, 3, 5, 7
fmt.Println(a)
fmt.Println(b)
fmt.Println(c)
fmt.Println(d)
}
Example
Prompt
Declare multiple variables of different types on the same line using var and :=.
Output: Go program and captured output
main.go
package main
import ("fmt")
func main() {
var a, b = 6, "Hello"
c, d := 7, "World!"
fmt.Println(a)
fmt.Println(b)
fmt.Println(c)
fmt.Println(d)
}
Go Variable Declaration in a Block
To make a group of declarations easier to read, you can also gather them into a single block:
Example
Prompt
Declare multiple variables in a block using var with parentheses and print them.
Output: Go program and captured output
main.go
package main
import ("fmt")
func main() {
var (
a int
b int = 1
c string = "hello"
)
fmt.Println(a)
fmt.Println(b)
fmt.Println(c)
}