BudiBadu Logo

Samplebadu

Code with Example
BudiBadu Logo
Samplebadu

Go by Example: String to Int

Go 1.23

Parsing strings into integers requires handling potential errors. Go provides `Atoi` for simple cases and `ParseInt` for more control.

Code

package main

import (
    "fmt"
    "strconv"
)

func main() {
    // 1. strconv.Atoi (Simple)
    // "Atoi" stands for ASCII to Integer.
    // Converts to 'int'. Returns value and error.
    s1 := "123"
    i1, err := strconv.Atoi(s1)
    if err != nil {
        panic(err)
    }
    fmt.Printf("Atoi: %d (type %T)\n", i1, i1)

    // 2. strconv.ParseInt (Advanced)
    // ParseInt(str, base, bitSize)
    // base: 0 (auto-detect), 10, 16, etc.
    // bitSize: 0 (int), 8, 16, 32, 64.
    s2 := "100"
    i2, err := strconv.ParseInt(s2, 10, 64)
    if err != nil {
        panic(err)
    }
    fmt.Printf("ParseInt: %d (type %T)\n", i2, i2)

    // 3. Handling Errors
    _, err = strconv.Atoi("invalid")
    if err != nil {
        fmt.Println("Error:", err)
    }
}

Explanation

Converting strings to integers involves parsing text that may not always be valid, so Go's functions for this task always return an error alongside the result. The most common function is strconv.Atoi (ASCII to Integer), which attempts to parse a string as a base-10 int. It is a convenient wrapper around the more general ParseInt function.

For scenarios requiring specific integer sizes (like int64) or different bases (like hexadecimal), strconv.ParseInt is used. It takes a base (0 to 64) and a bit size (0 to 64) as arguments. A base of 0 allows the function to infer the base from string prefixes like "0x" for hex. Always check the returned error to ensure the string was a valid number.

  • strconv.Atoi: Simple conversion to int.
  • strconv.ParseInt: Control over base and bit size (returns int64).
  • Error Handling: Always check for invalid syntax or range errors.

Code Breakdown

12
Using 'strconv.Atoi'. This is the most common way to parse a number. It returns an 'int' and an 'error'. If the string is "abc", err will be non-nil.
23
Using 'strconv.ParseInt'. The arguments are: string, base (10), and bitSize (64). Even if bitSize is 8 or 16, it always returns 'int64' to prevent overflow during parsing. You can cast it later.