Go Variables
Go gives you two ways to declare variables: the explicit var keyword and the shorthand := operator, both backed by type inference.
Declaring Variables with var
The var keyword declares a variable with an explicit type, an initial value, or both. It can be used both inside functions and at the package level, outside any function.
Using var
package main
import "fmt"
func main() {
var city string = "Bengaluru"
var population int = 8000000
fmt.Println(city, "has a population of", population)
}Short Variable Declaration with :=
Inside a function, the := operator declares and initializes a variable in one step, without stating a type. Go infers the type automatically from the value on the right.
Using :=
package main
import "fmt"
func main() {
city := "Bengaluru"
population := 8000000
fmt.Println(city, "has a population of", population)
}Type Inference
Whether you write var name = "Alice" or name := "Alice", Go looks at the literal "Alice" and infers that name has type string. Once inferred, the type is fixed — you cannot later assign an int to that same variable.
- var can appear at package level; := can only appear inside a function body
- var works with or without an initial value; := always requires one
- Multiple variables can be declared and assigned together on one line
- A variable declared but never used causes a compile error in Go
Multiple Variables at Once
package main
import "fmt"
func main() {
var x, y int = 10, 20
name, age := "Sam", 34
fmt.Println(x, y, name, age)
}Exercise: Go Variables
Which keyword declares a variable with an explicit type in Go?