Module lessons (1/5)
Variables and types
In Go every variable has a static type known to the compiler: once declared, a variable cannot change type. This rigidity — very different from JavaScript or Python — is the price you pay to get compile-time errors instead of runtime ones, small binaries, and predictable performance.
Two forms of declaration
var with explicit type
var name string = "Ada"
var age int = 36
var active boolWhen you omit the value (as in var active bool) the variable receives the
zero value of its type — we'll come back to this in the next lesson.
Short declaration :=
Inside a function you can use :=, which infers the type from the
expression on the right. It is the idiomatic form and the one you'll use
90% of the time:
name := "Ada" // string
age := 36 // int
pi := 3.14 // float64
active := true // boolThe basic types you'll meet right away
| Type | Example | Notes |
|---|---|---|
int | 42 | size depends on the CPU (32 or 64 bit) |
float64 | 3.14 | default for decimal literals |
string | "Ada" | UTF-8, immutable |
bool | true, false | no "truthy", only pure bool |
rune | 'A' | alias of int32, represents a Unicode code point |
byte | 0x7F | alias of uint8 |
There are also int8/16/32/64, uint8/16/32/64, float32 and complex64/128
for when you need precise sizes (binary parsing, interop, etc.).
Multiple declarations
You can declare several variables with a var-block or a plural :=:
var (
name string = "Ada"
age int = 36
active bool
)
x, y := 10, 20
a, b, c := "a", 2, true // different types: no problemVariables declared but not used
Go is strict: a variable declared and never used is a compilation
error, not a warning. The same applies to unused imports.
func main() {
x := 42
// error: x declared and not used
}To silence the rule temporarily you use _ (blank identifier):
_ = xYour turn
Use var to declare a variable name of type string with value 'Ada' and print it.
Show hint
The long form is `var <name> <type> = <value>`.
Solution available after 3 attempts
On a single line, use := to assign 36 to age and 'Roma' to city, then print both.
Show hint
You can assign multiple variables at once: `a, b := 1, "due"`.
Solution available after 3 attempts
Which of these declarations produces a compilation error if placed OUTSIDE a function?
// (a)
var name string = "Ada"
// (b)
age := 36
// (c)
const PI = 3.14Recap
- Static type, automatically inferred by
:=or declared withvar. :=only inside functions; at package level onlyvar/const.- Unused variables and imports = compilation error: use
_to silence them. int/float64/string/boolcover 90% of everyday cases.