To convert a string to int in Golang, you can use the “strconv.Atoi()”, “strconv.ParseInt()”, or “fmt.Sscan()” function.
Method 1: Using the strconv.Atoi() function
The strconv.Atoi() function accepts a string as its argument and returns an “int” type value.
Syntax
func Atoi(str string) (int, error)
Parameters
str: It is a string.
Example
package main
import (
"fmt"
"strconv"
)
func main() {
str := "1921"
op, err := strconv.Atoi(str)
if err != nil {
panic(err)
}
fmt.Printf("%T \n%v \n", op, op)
}
Output
int
1921
Method 2: Using the fmt.ParseInt() function
The ParseInt() function interprets a string in the given base (0, 2 to 36) and bit size (0 to 64) and returns the corresponding value.
Syntax
func ParseInt(str string, base int, bitSize int) (i int64, err error)
Parameters
- str: The string value to be converted into an integer number.
- base: The base value of the given value. It can range from 0, 2, to 36.
- bitSize: It specifies the integer type, such as int(0), int8(8), int16(16), int32(32), and int64(64).
Example
package main
import (
"fmt"
"strconv"
)
func main() {
str := "1921"
op, err := strconv.ParseInt(str, 10, 0)
if err != nil {
panic(err)
}
fmt.Printf("%T \n%v \n", op, op)
}
Output
int64
1921
And we get an integer converted from a string. The ParseInt() function takes a string, a base of 10, a bit size of 1, and returns an integer value.
Method 3: Using the fmt.Sscan() function
The fmt.Sscan() function scans string arguments and stores them into variables. It reads the string with spaces and assigns it to consecutive Integer variables.
Syntax
func Sscan(str string, a ...interface{}) (n int, err error)
Parameters
- str string: This parameter contains the specified text that will be scanned.
- a …interface{}: This parameter receives each text.
Example
package main
import (
"fmt"
"reflect"
)
func main() {
str_val := "19"
int_val := 21
_, err := fmt.Sscan(str_val, &int_val)
fmt.Println(int_val, err, reflect.TypeOf(int_val))
}
Output
19 <nil> int
That’s it.

Krunal Lathiya is a seasoned Computer Science expert with over eight years in the tech industry. He boasts deep knowledge in Data Science and Machine Learning. Versed in Python, JavaScript, PHP, R, and Golang. Skilled in frameworks like Angular and React and platforms such as Node.js. His expertise spans both front-end and back-end development. His proficiency in the Python language stands as a testament to his versatility and commitment to the craft.