Type Conversion
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,strconvfor 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 fitNumeric 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é" againstrconv 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.
The shortcut
Ask "is the value text, or is the target text?" If either is, it is strconv (or fmt.Sprintf). If both are numbers, or you are moving between string, []byte and []rune, it is T(v).
Text to number
The argument
"3"is text, the target isint:strconv.Atoi("3"), and checkerr.
Drills
Answer fast — trust the rule.
f := 2.99. What is int(f)?
What does strconv.Itoa(65) return?
What does string(rune(65)) return?
n, err := strconv.Atoi("12a"). What do you get?
x := 300. What is uint8(x)?
Remember
- No silent conversions:
T(v)for types,strconvfor text. - Shortcut: text on either side → strconv; numbers or string/bytes/runes →
T(v). - Trap:
string(65)is "A", not "65"; float → int truncates.
