Skip to main content
eLearner.app
Module 1 · Lesson 2 of 52/50 in the course~10 min
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

CategoryTypeZero value
Numericint, int64, float32, float64, uint, ...0
Booleanboolfalse
Stringstring"" (empty string)
Pointer*Tnil
Slice / Map / Channel[]T, map[K]V, chan Tnil
Function / Interfacefunc(...), interface{...}nil
StructT struct{...}all fields at their zero value
Go
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).

Go
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.

Go
var a int = 10
var b int64 = int64(a)  // obbligatorio

Conversion between numerics: watch out for truncation

Going from float64 to int truncates towards zero, it does not round:

Go
f := 3.9
i := int(f)   // 3, non 4
n := int(-3.9) // -3, non -4

String ↔ 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:

Go
import "strconv"

s := strconv.Itoa(42)        // "42"
n, err := strconv.Atoi("42") // 42, nil

We'll cover it in depth in the Stdlib module.

Your turn

Exercise#go.m1.l2.e1
Attempts: 0Loading…

Declare a variable counter of type int without initializing it and print it. Expected: 0.

Loading editor…
Show hint

Without an initializer the variable takes the zero value of the type.

Solution available after 3 attempts

Exercise#go.m1.l2.e2
Attempts: 0Loading…

Given the integer n=10, convert n to float64 and divide by 4. Print the result (expected 2.5).

Loading editor…
Show hint

Without the explicit conversion, `n / 4` is an integer division that gives 2.

Solution available after 3 attempts

Quiz#go.m1.l2.e3
Ready

What does this code print?

Go
f := 3.7
fmt.Println(int(f))
Answer options

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 use math.Round.
  • For string ↔ number use the strconv package (NOT a direct cast).