Convert String to Int, Int64, Uint64

This is one of those posts that won’t need a huge introduction. We want to convert a string into an integer. We’ll look at the different ways to do this (based on which sort of int you want). We’ll convert to int, uint and uint64 (though a int64 will be easy enough work out).

All examples we cover will be part of the strconv package - see docs.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
package main

import (
	"fmt"
	"strconv"
)

func main() {

	myStr := "7"

	// Convert String -> Int
	myInt, err := strconv.Atoi(myStr)
	if err != nil {
		panic(err)
	}

	fmt.Printf("%T %v -> %T %v \n", myStr, myStr, myInt, myInt)
	// = string 7 -> int 7

	// Convert String -> Int64
	myInt64, err := strconv.ParseInt(myStr, 10, 64)
	if err != nil {
		panic(err)
	}

	fmt.Printf("%T %v -> %T %v \n", myStr, myStr, myInt64, myInt64)
	// = string 7 -> int64 7

	// Convert String -> UInt64
	myUInt64, err := strconv.ParseUint(myStr, 10, 64)
	if err != nil {
		panic(err)
	}

	fmt.Printf("%T %v -> %T %v \n", myStr, myStr, myUInt64, myUInt64)
	// = string 7 -> uint64 7
}

golang convert str to int