dongxing2710 2019-04-30 09:17
浏览 295
已采纳

ParseInt无法转换为所需的类型

Here's my code:

package main

import (
    "fmt"
    "reflect"
    "strconv"
)

func main() {
   i, _ := strconv.ParseInt("10", 10, 8)
   fmt.Println(reflect.TypeOf(i))
}

I expect i to be 8-bits long (the 3rd argument to strconv.ParseInt). It is int64, however (and the docs state that strconv.ParseInt will return int64).

What's the point of ParseInt if it always returns int64 (why not just use Atoi?)

  • 写回答

3条回答 默认 最新

  • dqm74406 2019-04-30 09:20
    关注

    Note this from the function's doc:

    The bitSize argument 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. For a bitSize below 0 or above 64 an error is returned.

    So it's guaranteed that you can convert your result to a byte with byte(i).

    Go doesn't have generics yet, so having a single ParseInt that can accept pointers to multiple integer types is difficult. Instead the guarantee is done with the bitSize argument

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)
编辑
预览

报告相同问题?