寻找一种优雅的方式来解析整数

Right now I am doing the following in order to parse an integer from a string and then convert it to int type:

tmpValue, _ := strconv.ParseInt(str, 10, 64) //returns int64
finalValue = int(tmpValue)

It is quite verbose, and definitely not pretty, since I haven't found a way to do the conversion in the ParseInt call. Is there a nicer way to do that?

It seems that the function strconv.Atoi does what you want, except that it works regardless of the bit size of int (your code seems to assume it's 64 bits wide).

If you have to write that once in your program than I see no problem. If you need at several places you can write a simple specialization wrapper, for example:

func parseInt(s string) (int, error) {
        i, err := strconv.ParseInt(str, 10, 32)  // or 64 on 64bit tip
        return int(i), err
}

The standard library doesn't aim to supply (bloated) APIs for every possible numeric type and/or their combinations.

Don't forget to check for errors. For example,

package main

import (
    "fmt"
    "strconv"
)

func main() {
    s := "123"
    i, err := strconv.Atoi(s)
    if err != nil {
        fmt.Println(err)
        return
    }
    fmt.Println(i)
}

Output:

123