Module lessons (2/5)
Zero value and type conversions
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
| Category | Types | Zero value |
|---|---|---|
| Numeric | int, int64, float64, uint | 0 |
| Boolean | bool | false |
| String | string | "" (empty string) |
| Pointer / Function / Interface | *T, func(...), any | nil |
| Slice / Map / Channel | []T, map[K]V, chan T | nil |
| Struct | struct { ... } | Each field at its own zero value |
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.
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:
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:
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
Declare a variable counter of type int without initializing it (exploiting the zero value) and print it. Expected: 0.
Show hint
Use var counter int without = to let Go assign the zero value.
Solution available after 3 attempts
Given the integer n := 10, convert n to float64 and divide by 4 storing in result, then print it (expected 2.5).
Show hint
Convert the integer operand to float64(n) before executing / to get 2.5 instead of 2.
Solution available after 3 attempts
Convert raw := "128" to integer with strconv.Atoi: if err != nil print the error and exit with return, otherwise print parsed * 2.
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
What does this code print?
f := 3.7
fmt.Println(int(f))What does fmt.Println(strconv.Itoa(65)) print versus a rune conversion?
package main
import (
"fmt"
"strconv"
)
func main() {
fmt.Println(string(rune(65)), strconv.Itoa(65))
}