How to Convert string to integer type in Golang?

Strings in Golang is a sequence of variable-width characters where each and every character is represented by one or more bytes using UTF-8 Encoding. In Go language, both signed and unsigned integers are available in four different sizes. In order to convert string to integer type in Golang, you can use the following methods.

1. Atoi() Function: The Atoi stands for ASCII to integer and returns the result of ParseInt(s, 10, 0) converted to type int.

Syntax:

func Atoi(s string) (int, error)

Example:

filter_none

edit
close

play_arrow

link
brightness_4
code

// Go program to illustrate how to
// Convert string to the integer type
  
package main
  
import (
    "fmt"
    "strconv"
)
  
func main() {
  
    str1 := "123"
  
    // using ParseInt method
    int1, err := strconv.ParseInt(str1, 6, 12)
  
    fmt.Println(int1)
  
    // If the input string contans the integer
    // greater than base, get the zero value in return
    str2 := "123"
  
    int2, err := strconv.ParseInt(str2, 2, 32)
    fmt.Println(int2, err)
  
}

chevron_right


Output:



123
0 strconv.Atoi: parsing "12.3": invalid syntax

2. ParseInt() Function: The ParseInt interprets a string s in the given base (0, 2 to 36) and bit size (0 to 64) and returns the corresponding value i.

Syntax:

func ParseInt(s string, base int, bitSize int) (i int64, err error)

Example:

filter_none

edit
close

play_arrow

link
brightness_4
code

// Go program to illustrate how to
// Convert string to the integer type
  
package main
  
import (
    "fmt"
    "strconv"
)
  
func main() {
  
    str1 := "123"
  
    // using ParseInt method
    int1, err := strconv.ParseInt(str1, 6, 12)
  
    fmt.Println(int1)
  
    // If the input string contans the integer
    // greater than base, get the zero value in return
    str2 := "123"
  
    int2, err := strconv.ParseInt(str2, 2, 32)
    fmt.Println(int2, err)
  
}

chevron_right


Output:

51
0 strconv.ParseInt: parsing "123": invalid syntax



My Personal Notes arrow_drop_up

Small things always make you to think big

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.