strconv converts strings to basic Go types and formats typed values as strings. It is especially useful when CLI arguments, files, environment variables, or configuration values arrive as text and require validation before processing. section 10.9
Use strconv for controlled parsing and predictable output:
- Parse numeric strings with ParseInt, then handle malformed input and validate domain constraints such as a port range. section 10.9
- Parse Boolean configuration with ParseBool; accepted values include common true and false spellings plus 1, t, 0, and f. section 10.9
- Format integers, Booleans, and floating-point values with dedicated functions, choosing numeric base, notation, and precision where needed. section 10.9
- Prefer strconv over generic formatting when conversion performance and consistent representation matter. section 10.9
Validated configuration parsing
func parsePortNumber(portStr string) (int, error) { port, err := strconv.ParseInt(portStr, 10, 32) if err != nil { return 0, fmt.Errorf("invalid port number %q: %w", portStr, err) } if port < 1 || port > 65535 { return 0, fmt.Errorf("port must be between 1 and 65535, got %d", port) } return int(port), nil } The same pattern applies to ParseBool: return a contextual error when the input is invalid instead of silently accepting an unexpected value. section 10.9 section 10.9
Figure 10.5 The complete CLI tool architecture, showing all layers and components
Places string conversion within a complete CLI pipeline that accepts command-line input, validates it, converts structured data, and produces output. section 10.10

