Declaring Variables with var
In this page:
Basic var Declaration
The var keyword declares a variable with an explicit name and type: 'var age int'. Until you assign it a value, it holds the zero value for that type -- 0 for numbers, "" for strings, false for booleans. This is different from many languages where an uninitialized variable is undefined or an error.
Example: Basic var Declaration
package main
import "fmt"
func main() {
var age int
var name string
fmt.Println("age:", age)
fmt.Println("name:", name)
}
Login to try C/C++/Java/PHP code in the editor
Declaring and Initializing Together
You can supply an initial value in the same line as a var declaration: 'var age int = 30'. If an initializer is present, Go can often infer the type, letting you drop the explicit type entirely and write 'var age = 30'.
Example: Declaring and Initializing Together
package main
import "fmt"
func main() {
var age int = 30
var city = "Bengaluru"
fmt.Println(age, city)
}
Login to try C/C++/Java/PHP code in the editor
Declaring Multiple Variables
A single var block can declare several variables at once using parentheses, which keeps related declarations grouped and readable, especially at the top of a file for package-level variables.
Note: Grouping related variables in a var block is a common way to keep package-level declarations organized.
Example: Declaring Multiple Variables
package main
import "fmt"
var (
appName = "Inventory"
appVersion = "1.0"
maxItems = 100
)
func main() {
fmt.Println(appName, appVersion, maxItems)
}
Login to try C/C++/Java/PHP code in the editor
Package-Level vs Local Variables
Variables declared with var inside a function are local to that function, while var declarations outside any function, at the top level of a file, become package-level variables visible throughout the package. Package-level var is one of the few places Go allows a variable to exist without being immediately used.
Example: Package-Level vs Local Variables
package main
import "fmt"
var counter int
func increment() {
counter++
}
func main() {
increment()
increment()
fmt.Println("counter:", counter)
}
Login to try C/C++/Java/PHP code in the editor
- Declaring a var and never using it -- Go refuses to compile a function with an unused local variable.
- Forgetting that var declared without an initial value gets its type's zero value, not nil/undefined like in other languages.
- Redundantly writing the type when the initializer already makes it obvious, when := or type inference would be cleaner.
- 'var name type' declares a variable with an explicit type.
- 'var name type = value' declares and initializes in one step.
- Variables declared without a value get that type's zero value automatically.
- var can declare multiple variables at once inside a parenthesized block.
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: