Skip to content

Day 003 — Numeric & String Types, Conversions

Month 1 · Week 1 · ⬅ Day 002 · Day 004 ➡ · Journal index

🎯 Learning Objective

Understand Go's numeric/string types and convert between them correctly (including the string(int) trap).

📚 Topics

  • Sized integers, floats, byte/rune, explicit conversions
  • strconv for number↔string; bytes vs runes in strings

📖 Reading / Sources

📝 Notes

  • Go has no implicit numeric conversionfloat64(i), int(f), etc., always explicit. Prevents silent precision bugs.
  • Number ↔ string uses strconv, not conversion syntax. strconv.Itoa(42)"42"; strconv.Atoi("42")42, nil. ParseFloat/ParseInt/ParseBool for the rest.
  • ⚠️ string(65) is "A", not "65" — converting an int to string interprets it as a Unicode code point. Use strconv.Itoa for the digits.
  • Strings are immutable UTF-8 byte sequences. len(s) is byte count; indexing s[i] is a byte; range s yields runes (code points). é is 1 rune but 2 bytes → [[slice-internals]] vs runes.
  • byte = uint8, rune = int32 (aliases).

💻 Code Examples

n, err := strconv.Atoi("123") // string -> int (always returns an error to check)
s := strconv.Itoa(n)          // int -> string "123"
// len("héllo") == 6 bytes, but 5 runes

Full code: examples/types/main.go · Run: go run ./examples/types

🏋️ Exercises / Practice

Exercise Status Link
Temperature converter (C↔F↔K) exercises/.../temp-converter
Count bytes vs runes in a string examples/types

🐛 Mistakes Made

  • Used string(num) to print a number and got a weird glyph — the classic trap. Switched to strconv.Itoa / fmt.Sprintf("%d").
  • Forgot to handle the error from Atoi; the compiler forced me to.

❓ Open Questions

  • When to use fmt.Sprintf vs strconv? (strconv is faster/clearer for single values; Sprintf for formatting.)

🧠 Active Recall

  1. Q: What is len("héllo") and why?
    A6 — len counts bytes, and é is 2 bytes in UTF-8 (5 runes total).
  2. Q: How do you turn 42 into the string "42"?
    Astrconv.Itoa(42) (or fmt.Sprintf("%d", 42)). Not string(42).

🪶 Feynman Reflection

Go never quietly changes a number's type for you — you ask explicitly. Strings are just bytes that usually hold UTF-8 text, so "length" can mean bytes or characters; ranging gives you characters (runes).

🕳️ Knowledge Gaps

  • Deeper rune/grapheme handling (emoji, combining marks) — defer to Month 2 strings cheatsheet.

✅ Summary

I can convert numbers and strings correctly and reason about byte-vs-rune length.

⏭️ Next Steps / Prep for Tomorrow

  • Day 004: control flow (if, for, switch) + FizzBuzz.

Time spent Difficulty Confidence
100 min 🟦🟦⬜⬜⬜ 🟦🟦🟦⬜⬜

Suggested commit: feat(examples): types and conversions; temp converter (day 003)