Open In App

strconv.Atoi() Function in Golang With Examples

Last Updated : 21 Apr, 2020
Comments
Improve
Suggest changes
Like Article
Like
Report
Go language provides inbuilt support to implement conversions to and from string representations of basic data types by strconv Package. This package provides an Atoi() function which is equivalent to ParseInt(str string, base int, bitSize int) is used to convert string type into int type. To access Atoi() function you need to import strconv Package in your program. Syntax:
func Atoi(str string) (int, error)
Here, str is the string. Example 1: C
// Golang program to illustrate
// strconv.Atoi() function
package main

import (
    "fmt"
    "strconv"
)

func main() {

    // Using Atoi() function
    x := "245"
    y, e := strconv.Atoi(x)
    if e == nil {
        fmt.Printf("%T \n %v", y, y)
    }

}
Output:
int 
 245
Example 2: C
// Golang program to illustrate
// strconv.Atoi() function
package main

import (
    "fmt"
    "strconv"
)

func main() {

    // Using Atoi() function
    x1 := "245"
    fmt.Println("Before:")
    fmt.Printf("Type: %T ", x1)
    fmt.Printf("\nValue: %v", x1)
    y1, e1 := strconv.Atoi(x1)
    if e1 == nil {
        fmt.Println("\nAfter:")
        fmt.Printf("Type: %T ", y1)
        fmt.Printf("\nValue: %v", y1)
    }

    x2 := "1"
    fmt.Println("\n\nBefore:")
    fmt.Printf("Type: %T ", x2)
    fmt.Printf("\nValue: %v", x2)
    y2, e2 := strconv.Atoi(x2)
    if e2 == nil {
        fmt.Println("\nAfter:")
        fmt.Printf("Type: %T ", y2)
        fmt.Printf("\nValue: %v", y2)
    }

}
Output:
Before:
Type: string 
Value: 245
After:
Type: int 
Value: 245

Before:
Type: string 
Value: 1
After:
Type: int 
Value: 1

Next Article
Article Tags :

Similar Reads