liveBook · Manning

Strconv

As explained in Go in Action, Second Edition

strconv is a Go standard-library package for converting between strings and basic data types such as integers, floating-point numbers, and booleans.

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

How Go in Action, Second Edition covers it

How deep it goes
Explains parsing, validation, error handling, and formatting controls, but does not descend into conversion internals.
Examples
Uses port parsing with range validation, Boolean debug flags, and type-switched formatting for configuration display.
What you can do after
Apply strconv to parse validated configuration values and generate controlled string representations for logs, displays, and output.
How it connects
Connects string conversion with CLI tools, configuration files, environment variables, validation, error handling, and fmt.Sprintf.

Also explained in

Compare how 2 books explain strconv →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Go in Action, Second Edition. The section links point to the parts of the book it draws on.