Initialize multiple Variables in Single Line
To assign/initialize multiple Variables in a single line, specify the variables as comma separated on the left side of assignment operator, and the comma separated values on the right side of assignment operator.
In this tutorial, we will learn how to initialize multiple variables in a single line, with examples covering different scenarios based on number of variables assigned, and datatype of variables.
Examples
Assign Two Variables
In the following example, we will assign two variables, x
and y
, in a single statement with integer values.
Example.go
package main import "fmt" func main() { var x, y = 10, 20 fmt.Println(x) fmt.Println(y) }
Output
10 20
Assign Different Datatypes
Now, let us assign an integer and a string to variables in a single line.
Example.go
package main import "fmt" func main() { var x, y = 10, "Hello World" fmt.Println(x) fmt.Println(y) }
Output
10 Hello World
Assign Four Variables
Example.go
package main import "fmt" func main() { a, b, c, d := 10, "Hello World", true, 25.366 fmt.Println(a) fmt.Println(b) fmt.Println(c) fmt.Println(d) }
Output
10 Hello World true 25.366
Conclusion
In this Golang Tutorial, we learned how to initialize multiple variables in a single line in Go language, with the help of example programs.