Variables
Variables let you name values. Go uses explicit var declarations or short-hand := inside functions.
Key Points
varallows explicit types or inferred types from the initializer.:=is only valid inside functions; it infers the type.- Multiple assignment is common for parallel declarations.
- Uninitialized variables have their type's zero value, never undefined.
package main
import "fmt"
func main() {
var a string = "initial"
fmt.Println(a)
var b, c int = 1, 2
fmt.Println(b, c)
var d = true // type inferred
fmt.Println(d)
var e int // zero value
fmt.Println(e)
f := "short" // short declaration inside functions
fmt.Println(f)
}initial
1 2
true
0
shortVariable Declaration Syntax
| Declaration | Example | Scope | Description |
|---|---|---|---|
var name type | var x int | Package or Function | Explicit type, zero value initialized |
var name = value | var x = 10 | Package or Function | Type inferred from value |
name := value | x := 10 | Function only | Short declaration, type inferred |
var a, b type | var x, y int | Package or Function | Multiple variables, same type |
Zero Values
| Type | Zero Value |
|---|---|
int, int8, int16, int32, int64 | 0 |
float32, float64 | 0.0 |
bool | false |
string | "" (empty string) |
| Pointers, slices, maps, channels, functions, interfaces | nil |