The var
keyword in Go is used to declare variables. These can be done outside a function (and can be used throughout a program) or inside a function.
Similar to the const
keyword, var
can be used to group together several declarations. And it can replace uses of the new()
built-in function.
We can declare variables in a var
block. Here variables are initialized at runtime, and they can be reassigned in methods. They can be used throughout the program.
var
declaration that is at the file scope, and not part of any function body.var
within a func
. This value is available in all funcs in a file.var
in place of the new()
built-in. New()
returns a pointer, while var
returns the actual object data.package main
import "fmt"
// Part 1: use global var.
var position int
func main() {
// Part 2: adjust global var value.
position = 10
fmt.Println("Test1:", position)
position = 20
fmt.Println("Test2:", position)
// Part 3: use local var with single var block.
var (
color = "blue"
size = 10
)
fmt.Println("Color and size:", color, size)
// Part 4: use var and new to allocate an int.
var x int = 100
y := new(int)
*y = 100
fmt.Println(x, *y)
}Test1: 10
Test2: 20
Color and size: blue 10
100 100
short
syntaxWe can use the var
keyword with a type or without a type. We can declare variables with var
, but it is also possible to use a shorter syntax.
var
declaration with no type specified. The string
is assigned to different values and printed.short
variable declaration—it does the same thing as program version 1.package main import "fmt" func Test1() { // Version 1: use a local variable string. var animal = "Cat" fmt.Println("TEST1: " + animal) // Reassign the local variable. animal = "Dog" fmt.Println("TEST1: " + animal) } func Test2() { // Version 2: use short variable declaration. animal := "Cat" fmt.Println("TEST2: " + animal) // Reassign it. animal = "Dog" fmt.Println("TEST2: " + animal) } func main() { Test1() Test2() }TEST1: Cat TEST1: Dog TEST2: Cat TEST2: Dog
A var
declaration can have more than one variable in it, and each can have a separate value. But only one type can be used. All variables use the specified type.
package main
import "fmt"
func main() {
// Create two vars of type int32 on one line.
var n, y int32 = 100, 200
// Display variables.
fmt.Println(n)
fmt.Println(y)
}100
200
Var is used throughout Go programs to declare variables. It can be used inside, and outside of, functions—and it can group together related variables.