Here, We will see how to convert string into int in go. We can do it by using Atoi() and ParseInt() function in strconv package in go golang.
There are many ways to convert string into int value in go.
- Atoi()
- ParseInt()
By using Atoi()
—–
Function prototype:
func Atoi(s string) (int, error) Input Parameter: s: integer value in string format
Return value:
Atoi() function in strconv package returns
integer value of string.
Example with code:
package main
import (
"fmt"
"strconv"
)
func main() {
i := "20"
s, err := strconv.Atoi(i, )
if err != nil {
panic(err)
}
fmt.Printf("%T, %v\n", s, s)
}
Output:
int, 20
By using ParseInt()
—–
ParseInt() interprets a string in the given base (0, 2 to 36) and bit size (0 to 64) and returns the corresponding value.
Function prototype:
func ParseInt(s string, base int, bitSize int) (i int64, err error)
Input Parameter:
s: Integer value in string format
base: It could be 0, 2 to 36
bitSize: 0 to 64
Return value:
FormatInt() function in strconv package returns
string representation of i in the given base,
for 2 <= base <= 36.
Example with code:
package main
import (
"fmt"
"strconv"
)
func main() {
no := "-101"
s, err := strconv.ParseInt(no, 10, 32)
if err != nil {
fmt.Print(err)
}
fmt.Printf("%T, %v\n", s, s)
s, err = strconv.ParseInt(no, 16, 32)
if err != nil {
fmt.Print(err)
}
fmt.Printf("%T, %v\n", s, s)
s, err = strconv.ParseInt(no, 10, 64)
if err != nil {
fmt.Print(err)
}
fmt.Printf("%T, %v\n", s, s)
s, err = strconv.ParseInt(no, 16, 64)
if err != nil {
fmt.Print(err)
}
fmt.Printf("%T, %v\n", s, s)
}
Output:
int64, -101 int64, -257 int64, -101 int64, -257
To learn more about golang, Please refer given below link:
https://techieindoor.com/go-lang-tutorial/
References:
https://golang.org/doc/
https://golang.org/pkg/