Convert string to integer type in Go?

前端 未结 5 1972
误落风尘
误落风尘 2020-11-30 19:12

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?

5条回答
  •  情深已故
    2020-11-30 19:30

    Converting Simple strings

    The easiest way is to use the strconv.Atoi() function.

    Note that there are many other ways. For example fmt.Sscan() and strconv.ParseInt() which give greater flexibility as you can specify the base and bitsize for example. Also as noted in the documentation of strconv.Atoi():

    Atoi is equivalent to ParseInt(s, 10, 0), converted to type int.

    Here's an example using the mentioned functions (try it on the Go Playground):

    flag.Parse()
    s := flag.Arg(0)
    
    if i, err := strconv.Atoi(s); err == nil {
        fmt.Printf("i=%d, type: %T\n", i, i)
    }
    
    if i, err := strconv.ParseInt(s, 10, 64); err == nil {
        fmt.Printf("i=%d, type: %T\n", i, i)
    }
    
    var i int
    if _, err := fmt.Sscan(s, &i); err == nil {
        fmt.Printf("i=%d, type: %T\n", i, i)
    }
    

    Output (if called with argument "123"):

    i=123, type: int
    i=123, type: int64
    i=123, type: int
    

    Parsing Custom strings

    There is also a handy fmt.Sscanf() which gives even greater flexibility as with the format string you can specify the number format (like width, base etc.) along with additional extra characters in the input string.

    This is great for parsing custom strings holding a number. For example if your input is provided in a form of "id:00123" where you have a prefix "id:" and the number is fixed 5 digits, padded with zeros if shorter, this is very easily parsable like this:

    s := "id:00123"
    
    var i int
    if _, err := fmt.Sscanf(s, "id:%5d", &i); err == nil {
        fmt.Println(i) // Outputs 123
    }
    

提交回复
热议问题