Module lessons (2/5)
Zero value and type conversions
In Go every variable declared without an explicit value receives a
zero value: the "neutral value" of its type. It's a huge difference
from JavaScript, where let x; produces undefined, or C, where you end
up with garbage memory. No undefined, no UB: just zero.
The zero value table
| Category | Type | Zero value |
|---|---|---|
| Numeric | int, int64, float32, float64, uint, ... | 0 |
| Boolean | bool | false |
| String | string | "" (empty string) |
| Pointer | *T | nil |
| Slice / Map / Channel | []T, map[K]V, chan T | nil |
| Function / Interface | func(...), interface{...} | nil |
| Struct | T struct{...} | all fields at their zero value |
var i int // 0
var f float64 // 0
var s string // ""
var b bool // false
var p *int // nil
var nums []int // nil (NB: una slice nil ha len 0 e si può iterare!)Conversions are ALWAYS explicit
Unlike C, Python or JS, Go does not automatically promote one
numeric type to another: you must write type(value).
i := 42
var f float64 = float64(i)
var u uint = uint(i)This is true even for "compatible" types like int and int64: an
explicit conversion is always required.
var a int = 10
var b int64 = int64(a) // obbligatorioConversion between numerics: watch out for truncation
Going from float64 to int truncates towards zero, it does not
round:
f := 3.9
i := int(f) // 3, non 4
n := int(-3.9) // -3, non -4String ↔ number conversion
string(65) does NOT give "65": it gives "A" (the rune with code
point 65). For string → number and vice versa you need the strconv
package:
import "strconv"
s := strconv.Itoa(42) // "42"
n, err := strconv.Atoi("42") // 42, nilWe'll cover it in depth in the Stdlib module.
Your turn
Declare a variable counter of type int without initializing it and print it. Expected: 0.
Show hint
Without an initializer the variable takes the zero value of the type.
Solution available after 3 attempts
Given the integer n=10, convert n to float64 and divide by 4. Print the result (expected 2.5).
Show hint
Without the explicit conversion, `n / 4` is an integer division that gives 2.
Solution available after 3 attempts
What does this code print?
f := 3.7
fmt.Println(int(f))Recap
- Every type has a consistent zero value: no
undefined, no UB. - Slice/map/chan/func/interface/pointer have zero value
nil. - Numeric conversions are always explicit with
type(value). int(float)truncates towards zero; to round usemath.Round.- For string ↔ number use the
strconvpackage (NOT a direct cast).