Lesson 2: Variables¶
Big Picture¶
flowchart LR
subgraph "Declaration styles"
A["var name = Go<br/>explicit type"]
B["var age = 25<br/>type inference"]
C["count := 10<br/>short declaration<br/>(functions only)"]
end
D["No initializer?"] --> E["Zero value:<br/>int→0 · string→empty · bool→false"]
F["const pi = 3.14"] -.->|"cannot be reassigned"| G[("Immutable")]
var works anywhere; := is a shortcut only allowed inside functions. Pick := when the type is obvious — it's the idiomatic default.
Concepts¶
Declaration Methods¶
// Explicit type
var name string = "Go"
// Type inference
var age = 25
// Short declaration (inside functions only)
count := 10
Constants¶
Zero Values¶
Variables declared without initialization get zero values:
| Type | Zero value |
|---|---|
int |
0 |
string |
"" |
bool |
false |
float64 |
0.0 |
Code Walkthrough¶
Full program: code/02_variables.go.
Try it yourself
Exercises
- Declare a variable with
varand no initializer — print its zero value. - Try assigning a string to an
intvariable — what does the compiler say? - Extend
ScanInputto read a third input.
Check Your Understanding¶
#
Where can the short declaration := be used?
#
What is the zero value of a declared-but-uninitialized bool?