Skip to main content
Module 1 · Lesson 2 of 52/50 in the course~10 min
Module lessons (2/5)

Zero value and type conversions

Explore Stage

Deterministic memory and safe casts

Take advantage of Go's zero-value utility and convert numbers and strings without hidden coercion.

In Go, any variable declared without an explicit value automatically receives a zero value, the deterministic neutral value of its type. No undefined like in JavaScript and no junk memory like in C.

Table of zero values

CategoryTypesZero value
Numericint, int64, float64, uint0
Booleanboolfalse
Stringstring"" (empty string)
Pointer / Function / Interface*T, func(...), anynil
Slice / Map / Channel[]T, map[K]V, chan Tnil
Structstruct { ... }Each field at its own zero value
Go
package main

import "fmt"

func main() {
	var count int      // 0
	var ratio float64  // 0
	var label string   // ""
	var active bool    // false
	var items []int    // nil (len = 0, pronta per append)

	fmt.Printf("%d %v %q %t %v\n", count, ratio, label, active, items == nil)
}

Explicit numeric conversions

Unlike C, Python, or JavaScript, Go does not automatically promote one numeric type to another: even between int and int64, explicit conversion to TargetType(val) is needed.

Go
package main

import "fmt"

func main() {
	total := 10
	divisor := 4

	intDiv := total / divisor               // 2 (divisione tra int)
	exactDiv := float64(total) / float64(divisor) // 2.5

	var wide int64 = int64(total)
	fmt.Println(intDiv, exactDiv, wide)
}

Truncation towards zero from float to int

Converting a floating point number to int truncates the decimal part towards zero, without rounding:

Go
package main

import (
	"fmt"
	"math"
)

func main() {
	price := 3.9
	fmt.Println(int(price))             // 3
	fmt.Println(int(-3.9))            // -3
	fmt.Println(int(math.Round(price))) // 4
}

Converting between strings and numbers

Beware of a classic beginner's mistake: string(65) does NOT produce "65", but interprets 65 as a Unicode code point and returns "A". To convert between decimal text representation and numbers use strconv:

Go
package main

import (
	"fmt"
	"strconv"
)

func main() {
	asChar := string(rune(65))   // "A"
	asText := strconv.Itoa(65)   // "65"
	n, err := strconv.Atoi("42") // 42, nil

	fmt.Println(asChar, asText, n, err)
}

Guided practice

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

Declare a variable counter of type int without initializing it (exploiting the zero value) and print it. Expected: 0.

Loading editor…
Show hint

Use var counter int without = to let Go assign the zero value.

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 storing in result, then print it (expected 2.5).

Loading editor…
Show hint

Convert the integer operand to float64(n) before executing / to get 2.5 instead of 2.

Solution available after 3 attempts

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

Convert raw := "128" to integer with strconv.Atoi: if err != nil print the error and exit with return, otherwise print parsed * 2.

Loading editor…
Show hint

strconv.Atoi(raw) returns (int, error): Handle the error with if err != nil before multiplying parsed * 2.

Solution available after 3 attempts

Check for understanding

Quiz#go.m1.l2.e3
Ready

What does this code print?

Go
f := 3.7
fmt.Println(int(f))
Answer options
Quiz#go.m1.l2.e5
Ready

What does fmt.Println(strconv.Itoa(65)) print versus a rune conversion?

Go
package main

import (
	"fmt"
	"strconv"
)

func main() {
	fmt.Println(string(rune(65)), strconv.Itoa(65))
}
Answer options