The strconv Package
Start with The strconv Package
The strconv package converts values to and from their textual representations with explicit error handling.
What you’ll learn
- Explain the main purpose of the strconv package.
- Read and run the complete Go example in this lesson.
- Apply the concept and recognize common mistakes.
Understand the idea
strconv.Atoi parses a base-10 integer and returns (int, error). strconv.Itoa converts an integer to its decimal string. For more control use ParseInt, ParseFloat and FormatFloat.
Parsing can fail because text is invalid or a number is out of range; always inspect the error before relying on the returned numeric value. A string containing spaces may need trimming first.
Visualize how it works
Follow this diagram before executing the example. Check where a value or decision changes what runs next.
Run a complete Go example
This example is a complete program. Save it as main.go or paste it into the Go Playground.
Go code
package main
import (
"fmt"
"strconv"
)
func main() {
count, err := strconv.Atoi("42")
if err != nil {
fmt.Println("Error:", err)
return
}
fmt.Println("Plus one:", count+1)
fmt.Println("As text:", strconv.Itoa(count))
_, err = strconv.Atoi("four")
fmt.Println("Invalid input:", err != nil)
}
Output
Plus one: 43
As text: 42
Invalid input: trueTrace what the program does
Parsing "42" produces integer 42, which is incremented to 43. Itoa returns the string "42". Parsing "four" fails, yielding a non-nil error.
Avoid common mistakes
- An invalid parse does not return a trustworthy numeric result.
- strconv.Atoi does not silently ignore surrounding whitespace.
Try it yourself
Parse the text "3.14" with strconv.ParseFloat and display it with two decimals.
Tip: Edit the example above, predict the output, and run the modified code to test your reasoning.
Check your understanding
What you should remember
You have practiced The strconv Package in a small, self-contained program. The important habit is to predict what runs, inspect the actual output and distinguish the language rule from the particular example.
Before continuing, make sure you can explain the program to someone who has not seen it, including the line that changes its result.
Reaching the recap and completing the quizzes are separate milestones.