๐Ÿ”„strconv โ€” String ConversionsLESSON

Why strconv?

Real programs constantly convert between strings and numbers: parsing URL query parameters, reading environment variables, formatting IDs, serialising config. The strconv package is the standard library's dedicated module for these conversions โ€” faster and more explicit than fmt.Sprintf / fmt.Sscanf.

int โ†” string

Atoi = ASCII to integer. Itoa = integer to ASCII. These are the most common calls in real Go code.

ParseInt โ€” control base and bit size

strconv.ParseUint and strconv.FormatInt(n, base) mirror this API.

float64 โ†” string

Format verbs: 'f' = decimal, 'e' = scientific, 'g' = shortest of f/e.

bool โ†” string

ParseBool accepts: "1", "t", "T", "TRUE", "true", "True", "0", "f", "F", "FALSE", "false", "False".

Handling *strconv.NumError

When parsing fails, the error is a *strconv.NumError with structured fields:

Quote and Unquote

Useful for generating code, writing config parsers, and producing safe debug output.

strconv vs fmt for performance

strconv.Itoa(n) is measurably faster than fmt.Sprintf("%d", n) because it avoids reflection and interface boxing. In hot paths (log lines, IDs, counters), prefer strconv.

Knowledge Check

What does strconv.Atoi("abc") return?

Which strconv.FormatFloat format verb produces the shortest decimal representation?

Why prefer strconv.Itoa over fmt.Sprintf("%d", n) in a hot path?