strconv.Atoi() Function in Golang With Examples

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:

filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


Output:

int 
 245

Example 2:

filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


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

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.