Skip to the workspace
Pebellslearn by building
Strings and Type Conversion  ›  Capstone Project

Type Conversion

Type Conversion 15 minA conversion such as T(v) explicitly produces a value of another type. Text parsing uses operations such as those in strconv, which can report invalid input.

golang / Type Conversion

Explore each scene at your own pace.

01 · The rule

The rule

Type Conversion

A conversion such as T(v) explicitly produces a value of another type. Text parsing uses operations such as those in strconv, which can report invalid input.

Make numeric conversions explicit and handle parsing errors at text boundaries.

The user runs tally -top 3 notes.txt. That 3 arrives as text, but tally needs an int to slice the results, and later it needs text again to print "showing 3 words". Go will not guess any of these steps for you. You convert explicitly, with the right tool for each direction.

The rule

No silent conversions: T(v) for types, strconv for text.

T(v) between compatible types. Write the target type like a function:

total, lines := 17, 4
avg := float64(total) / float64(lines) // 4.25

f := 3.9
n := int(f)       // 3: truncates toward zero
m := int(-f)      // -3

big := 200
small := int8(big) // -56: wraps to fit

Numeric conversions can lose information — the fraction, or the high bits — and Go assumes you meant it. With constants the compiler checks: int8(200) written with a literal is a compile error.

Strings, bytes and runes convert with T(v) too:

b := []byte("café")   // 5 bytes
r := []rune("café")   // 4 runes
s := string(r)        // "café" again

strconv for text ↔ numbers. Parsing text can fail, so it returns an error:

top, err := strconv.Atoi("3")  // 3, nil
_, err = strconv.Atoi("three") // 0, an error
label := strconv.Itoa(3)       // "3"
p, _ := strconv.ParseFloat("4.25", 64)

When would you convert to []byte? Whenever an API wants bytes: writing to a file with os.WriteFile, hashing, or network code. Converting a string to []byte copies the data, because the string must stay immutable while the byte slice can change.

The famous trap: string(65) does not give "65". It treats 65 as a code point and gives "A". go vet warns about it, precisely because it is almost always a mistake. int("3") does not even compile.

Scene 1 of 5
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.