The Wayback Machine - https://web.archive.org/web/20220531073702/https://www.geeksforgeeks.org/strconv-atoi-function-in-golang-with-examples/
Skip to content
Related Articles

Related Articles

strconv.Atoi() Function in Golang With Examples

Improve Article
Save Article
Like Article
  • Difficulty Level : Easy
  • Last Updated : 21 Apr, 2020

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:




// 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:




// 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

My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!