将字符串解析为int的特定类型(int8,int16,int32,int64)

I am trying to parse a string into an integer in Go. The Problem I found with it is in the documentation its mentioned syntax is as follows:

ParseInt(s string, base int, bitSize int)

where, s is the string to be parsed, base is implied by the string's prefix: base 16 for "0x", base 8 for "0", and base 10 otherwise.

The bitSize parameter is where I am facing problem. As per documentation of ParseInt, it specifies the integer type that the result must fit into. Bit sizes 0, 8, 16, 32, and 64 correspond to int, int8, int16, int32, and int64.

But for all the values like 0, 8, 16, 32, and 64. I am getting same type return value. I.e of int64 type.

Could anyone point me out what am I missing.

Code: https://play.golang.org/p/F3LbUh_maY

As per documentation

func ParseInt(s string, base int, bitSize int) (i int64, err error)

ParseInt always return int64 no matter what. Moreover

The bitSize argument specifies the integer type that the result must fit into

So basically the your bitSize parameter only tells that the string value that you are going to parse should fit the bitSize after parsing. If not, out of range will happen.

Like in this PlayGround: strconv.ParseInt("192", 10, 8) (as you see the value after the parsing would be bigger than maximum value of int8).

If you want to parse it to whatever value you need, just use int8(i) afterwards (int8, int16, int32).

P.S. because you touched the topic how to convert to specific intX, I would outline that it is also possible to convert to unsigned int.

ParseInt always returns an int64, and you need to convert the result to your desired type. When you pass 32 as the third argument, then you'll get a parse error if the parsed value won't fit into an int32, but the returned type is always int64.

For example:

i, err := strconv.ParseInt("9207", 10, 32)
if err != nil {
    panic(err)
}
result := int32(i)
fmt.Printf("Parsed int is %d
", result)

About string conversion to int,I did a test, I recommend the way 2(strconv.Atoi("1339882")):

func BenchmarkGetN(b *testing.B)  {
    b.ResetTimer()
    for i := 0; i < b.N; i++ {
        i, err := strconv.ParseInt("1339882", 10, 32)
        if err != nil {
            panic(err)
        }
        a := int32(i)
        _ = a
    }
}

func BenchmarkGetN2(b *testing.B) {
    b.ResetTimer()
    for i := 0; i < b.N; i++ {
        a, _ := strconv.Atoi("1339882")
        bc := int32(a)
        _ = bc
    }
}
goos: darwin
goarch: amd64
pkg: phonedata
BenchmarkGetN-4         100000000               20.0 ns/op
BenchmarkGetN2-4        200000000                9.25 ns/op
PASS
ok      phonedata       10.913s