Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert string to integer type in Go?

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?

like image 912
Matt Joiner Avatar asked Nov 25 '10 15:11

Matt Joiner


People also ask

How do I convert type in Golang?

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.

How do you convert something to string in Go?

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.


1 Answers

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) } 
like image 113
peterSO Avatar answered Oct 10 '22 06:10

peterSO