Introduction
In Go, variables are explicitly declared and the compiler uses them to check type-correctness of function calls. Go provides multiple ways to declare variables, from explicit declarations to type inference and shorthand syntax.The Code
Variable Declaration Methods
Basic Declaration with Initialization
var keyword declares a variable. When you provide an initial value, Go infers the type automatically.
Multiple Variable Declaration
int type.
Type Inference
d is a bool based on the initial value true.
Zero Values
0for numeric typesfalsefor booleans""(empty string) for stringsnilfor pointers, slices, maps, channels, functions, and interfaces
There’s no “undefined” or “null” in Go. Every variable always has a value, even if you don’t explicitly initialize it.
Short Declaration (:=)
:= syntax is shorthand for declaring and initializing a variable. This is equivalent to var f string = "apple" but more concise.
The
:= syntax is only available inside functions. At package level, you must use the var keyword.Declaration Styles Comparison
| Style | Example | When to Use |
|---|---|---|
var with type and value | var x int = 10 | When you want to be explicit |
var with inference | var x = 10 | When type is obvious from value |
var without value | var x int | When you want zero value |
| Short declaration | x := 10 | Most common inside functions |
Key Takeaways
- Use
varfor explicit variable declarations - Go infers types when you provide initial values
- Uninitialized variables get their type’s zero value
- The
:=shorthand is convenient for function-local variables :=can only be used inside functions, not at package level- Variables in Go are always typed - no dynamic typing