Convert String to Integer in Go
To convert a string to an integer in Go, use strconv.Atoi(). It accepts a base-10 integer string and returns two values: the converted int and an error.
Always check the returned error before using the integer. Invalid text, an empty string, or a value outside the range of int causes the conversion to fail.
Go String-to-Integer Syntax with strconv.Atoi
The sample code snippet to use Atoi() function is given in the following.
// import statement
import "strconv"
// convert string to integer
number, error = strconv.Atoi("14")
strconv.Atoi() returns an int and an error value. The error is nil when the complete string represents a valid base-10 integer.
Atoi is a convenient shorthand for parsing a base-10 string into an int. Use strconv.ParseInt() when you need to choose the numeric base or bit size.
Convert a Valid Numeric String to int
In the following program, str contains only decimal digits. The call to strconv.Atoi() converts it to an int.
example.go
package main
import "fmt"
import "strconv"
func main() {
var str = "14"
// convert string to integer
number, error := strconv.Atoi(str)
fmt.Println("error:", error)
fmt.Println("number:", number)
}
Output
error: <nil>
number: 14
The same function accepts an optional leading plus or minus sign, so strings such as "-25" and "+8" are valid decimal integers.
Handle Invalid Integer Strings Returned by Atoi
In the following program, the string contains non-numeric characters. Since the entire string is not a valid integer, strconv.Atoi() returns an error.
example.go
package main
import "fmt"
import "strconv"
func main() {
var str = "14sup."
// convert string to integer
number, error := strconv.Atoi(str)
fmt.Println("error:", error)
fmt.Println("number:", number)
}
Output
error: strconv.Atoi: parsing "14sup.": invalid syntax
number: 0
The returned integer is not meaningful when error is non-nil. Check the error first instead of relying on the zero value.
number, err := strconv.Atoi(str)
if err != nil {
fmt.Println("invalid integer:", err)
return
}
fmt.Println(number)
Remove Leading and Trailing Spaces Before Conversion
strconv.Atoi() does not ignore surrounding whitespace. For input collected from a form, file, or command line, trim spaces explicitly with strings.TrimSpace().
package main
import (
"fmt"
"strconv"
"strings"
)
func main() {
text := " 42\n"
cleaned := strings.TrimSpace(text)
number, err := strconv.Atoi(cleaned)
if err != nil {
fmt.Println("conversion failed:", err)
return
}
fmt.Println(number)
}
Output
42
Convert String to int64 with strconv.ParseInt
Use strconv.ParseInt() when the result must have a defined size, such as int64, or when the input may use a base other than decimal.
value, err := strconv.ParseInt(text, base, bitSize)
The base argument controls how digits are interpreted. A base of 10 parses decimal input. The bitSize argument controls the permitted range; use 64 for an int64 result.
package main
import (
"fmt"
"strconv"
)
func main() {
text := "922337203685477580"
number, err := strconv.ParseInt(text, 10, 64)
if err != nil {
fmt.Println("conversion failed:", err)
return
}
fmt.Printf("%d (%T)\n", number, number)
}
Output
922337203685477580 (int64)
Parse Binary, Octal, and Hexadecimal Integer Strings
With strconv.ParseInt(), passing 0 as the base lets Go infer the base from a prefix such as 0b, 0o, or 0x.
package main
import (
"fmt"
"strconv"
)
func main() {
for _, text := range []string{"0b1010", "0o12", "0xA"} {
number, err := strconv.ParseInt(text, 0, 64)
if err != nil {
fmt.Println(err)
continue
}
fmt.Println(number)
}
}
Output
10
10
10
Convert String to uint in Go
For unsigned values, use strconv.ParseUint(). It rejects negative input and returns a uint64, which you can convert to a smaller unsigned type only after choosing a suitable bit size.
package main
import (
"fmt"
"strconv"
)
func main() {
text := "255"
value, err := strconv.ParseUint(text, 10, 8)
if err != nil {
fmt.Println("conversion failed:", err)
return
}
number := uint8(value)
fmt.Printf("%d (%T)\n", number, number)
}
Output
255 (uint8)
Atoi and ParseInt Differences in Go
| Requirement | Recommended function |
|---|---|
Convert a decimal string to the platform-sized int type | strconv.Atoi() |
Convert to int64 or enforce a specific signed range | strconv.ParseInt() |
| Parse binary, octal, decimal, or hexadecimal input | strconv.ParseInt() |
| Convert to an unsigned integer | strconv.ParseUint() |
Atoi() is effectively the simplest choice for ordinary base-10 input. ParseInt() provides explicit control over the base and bit size.
Integer Conversion Errors to Check in Go
- Invalid syntax: the string is empty or contains characters that are not valid for the selected base.
- Surrounding spaces: trim the input before parsing when whitespace is allowed.
- Range overflow: the value does not fit in the requested bit size or in the local
inttype. - Ignoring the error: do not use the returned number unless
err == nil. - Partial values: functions in
strconvexpect the whole string to represent the number; they do not extract a numeric prefix from arbitrary text.
Frequently Asked Questions About Go String-to-Integer Conversion
What does strconv.Atoi do in Go?
strconv.Atoi() converts a base-10 string to an int. It returns the integer and an error, so the caller can detect invalid input or a value that is outside the supported int range.
How do I convert a Go string to int64?
Call strconv.ParseInt(text, 10, 64). The returned value already has type int64.
How do I convert a string to uint in Go?
Use strconv.ParseUint(). Select the base and bit size, check the error, and then convert the returned uint64 to the required unsigned type when appropriate.
Does strconv.Atoi accept spaces or decimal points?
No. Trim surrounding spaces before conversion. A string containing a decimal point, such as "12.5", is not an integer; use strconv.ParseFloat() for floating-point input.
Why does Atoi return zero with an error?
For an invalid string, the numeric return value should not be used. The important result is the non-nil error. Check err before reading or storing the integer.
Editorial QA Checklist for Go Integer Parsing Examples
- Verify that every
Atoi,ParseInt, orParseUintcall checks the returned error. - Confirm that decimal, signed, unsigned, and prefixed-base examples use the intended parsing function.
- Check that the selected bit size matches the destination type and expected numeric range.
- Ensure whitespace is trimmed only when the input specification permits it.
- Run each example and confirm that its displayed output matches the program.
Summary of Converting Strings to Integers in Go
Use strconv.Atoi() for a normal decimal string-to-int conversion. Use strconv.ParseInt() for a specified base or signed bit size, and strconv.ParseUint() for unsigned values. In every case, validate the returned error before using the parsed number.
In this Go Tutorial, we learned how to convert a String to Integer in Go language, with example programs.
TutorialKart.com