Go Multi-Variable Declaration
Multi-Variable Declaration
It is possible to declare multiple variables in the same line.
Example
This example shows how multiple variables are declared.
package main
import ("fmt")
func main() {
var a, b int
var c, d int = 3, 5
fmt.Println(a)
fmt.Println(b)
fmt.Println(c)
fmt.Println(d)
}
Try it Yourself »
Note: When using the var
keyword with type
, it is only possible to declare one type of variable per line.
When the type of variable is not declared, it is possible to declare different types of variables in the same line.
Example
This example shows how multiple types of variables are declared.
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)
}
Try it Yourself »
Go Variable Declaration in a Block
Multiple variable declarations can be grouped together into a block for greater readability.
Example
package main
import ("fmt")
func main() {
var (
a int
b int = 1
c string = "hello"
)
fmt.Println(a)
fmt.Println(b)
fmt.Println(c)
}
Try it Yourself »