I'm trying to convert a string returned from flag.Arg(n)
to an int
. What is the idiomatic way to do this in Go?
Type conversion happens when we assign the value of one data type to another. Statically typed languages like C/C++, Java, provide the support for Implicit Type Conversion but Golang is different, as it doesn't support the Automatic Type Conversion or Implicit Type Conversion even if the data types are compatible.
You can convert numbers to strings by using the strconv. Itoa method from the strconv package in the Go standard libary. If you pass either a number or a variable into the parentheses of the method, that numeric value will be converted into a string value.
For example,
package main import ( "flag" "fmt" "os" "strconv" ) func main() { flag.Parse() s := flag.Arg(0) // string to int i, err := strconv.Atoi(s) if err != nil { // handle error fmt.Println(err) os.Exit(2) } fmt.Println(s, i) }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With