ParseInt无法转换为所需的类型 [英] ParseInt doesn't convert to the desired type

查看:46
本文介绍了ParseInt无法转换为所需的类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的代码:

软件包主要

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

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

我希望 i 的长度为8位( strconv.ParseInt 的第三个参数).但是它是int64(并且文档指出 strconv.ParseInt 将返回int64).

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).

如果ParseInt总是返回int64(为什么不仅仅使用Atoi?),那又有什么意义呢?

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

推荐答案

从函数文档中注意:

bitSize参数指定结果必须必须的整数类型适合.位大小0、8、16、32和64对应于int,int8,int16,int32和int64.对于小于0或大于64的bitSize,将出现错误返回.

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.

因此可以保证您可以将结果转换为带有 byte(i)的字节.

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

Go还没有泛型,因此很难拥有一个可以接受指向多个整数类型的指针的 ParseInt .相反,保证是通过 bitSize 参数

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

这篇关于ParseInt无法转换为所需的类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆