Go - Variables & Constants
Beginner 10/10
Teacher 10/10
Architect 10/10
Try it: Declare a variable with
var and another with :=. Print both values with fmt.Println.Declaring
var a int = 1
var b = 2 // inferred
aLong := 3 // function scope only
const Version = "1.0.0"
Multiple and Grouped
var (
i int
s string
)
const (
Pi = 3.14159
E = 2.71828
)
Naming
- Exported names start with uppercase:
MyType. - Keep names short and meaningful; prefer clarity.
Common errors
- Using
:=at package scope (allowed only inside functions). - Re-declaring a variable with
:=in the same scope unintentionally—use=to assign.
Practice
- Create grouped
varandconstblocks; print their values withfmt.Printf.
Quick quiz
- When do you use
varvsconst?
Show answer
Useconst for compile-time constants; var for values that may change.