Standard library patterns · 3 MIN READ

strconv is how text becomes a number

Parse a port with Atoi and reject anything outside 1…65535.

The Tour's Errors page uses strconv.Atoi as the example of a function that returns (int, error). That is the package: no ParseInt surprises in everyday code, no fmt.Sscan for a single number. Atoi is ParseInt(s, 10, 0) with a shorter name.

Failure is an error, not a panic and not a zero you are meant to guess at. Discarding that error is how "x" becomes port 0.

SEE THE IDEA

Text parsing returns a value and a failure path

  1. 01

    Text input

    go
    "42"

    May contain invalid or out-of-range data

  2. 02

    Parse

    go
    n, err := strconv.Atoi(text)

    Conversion must be checked

  3. 03

    Typed result

    go
    n

    Use only after the error decision

strconv parses representations; a numeric type conversion does not parse a string.

In practice

Use ParseInt with an explicit base and bit size when the data format requires a specific integer representation. Atoi targets int, whose width depends on the architecture. Distinguish syntax errors from out-of-range values when the user needs a useful message.

Watch out

Whitespace is not automatically trimmed by Atoi. Decide whether your input contract allows it and normalize explicitly.

Official reference ↗

Work through the exercise

go
package main

// ParsePort accepts 1 through 65535. Anything else is an error,
// including text that is not a number.
func ParsePort(raw string) (int, error) {
	return 0, nil
}

func main() {}
Try it yourself

Trace each value and write down your reasoning. Copy the source into GopherForge or your local Go environment to compile and check it. This web page does not execute your code or send it to a compiler service.

Progress stays in this browser. No account needed.