有一个名为”int32″的内置函数吗?

huangapple go评论88阅读模式
英文:

Is there a builtin func named "int32"?

问题

下面的代码片段运行正常。
在这种情况下,"int32"是什么?是一个函数吗?
我知道有一种叫做"int32"的类型。

这可能是一个愚蠢的问题。我刚刚完成了《Go之旅》但是我找不到答案。(可能是我漏掉了什么。)

package main

import "fmt"

func main() {
    var number = int32(5)
    fmt.Println(number) //5
}
英文:

The below snippet works fine.<br>
In this case, what "int32" is? A func?<br>
I know there is a type named "int32"<br><br>
This could be a stupid question. I've just finished A Tour of Go but I could not find the answer.(it's possible I'm missing something.)

package main

import &quot;fmt&quot;

func main() {
    var number = int32(5)
    fmt.Println(number) //5
}

答案1

得分: 10

这是一种类型转换,在处理数值类型时需要使用。

当在表达式或赋值中混合使用不同的数值类型时,就需要进行类型转换。例如,int32和int虽然在特定的架构上可能具有相同的大小,但它们并不是相同的类型。

由于你进行了变量声明,你需要指定'5'的类型。
另一个选项是,如rightfold评论中提到的:var number int32 = 5

(与短变量声明 number := 5 相对应)

另请参阅Go FAQ

在C语言中,数值类型之间的自动转换的方便性被造成的混淆所抵消。
表达式何时是无符号的?值有多大?是否会溢出?结果是否可移植,与执行的机器无关?

它还使编译器变得复杂;“通常的算术转换”不容易实现,并且在不同的架构上不一致。

为了可移植性的原因,我们决定以一些显式的转换为代价,使事情变得清晰和简单。Go中常量的定义——没有符号和大小注释的任意精度值——在很大程度上改善了这个问题。

一个相关的细节是,与C语言不同,即使int是64位类型,intint64也是不同的类型。
int类型是泛型的;如果你关心一个整数占用多少位,Go鼓励你明确指定

英文:

It is a type conversion, which is required for numeric types.

> Conversions are required when different numeric types are mixed in an expression or assignment. For instance, int32 and int are not the same type even though they may have the same size on a particular architecture.

Since you do a variable declaration, you need to specify the type of '5'.
Another option, as mentioned by rightfold in the comments is: var number int32 = 5

(as opposed to a short variable declaration like number := 5)

See also Go FAQ:

> The convenience of automatic conversion between numeric types in C is outweighed by the confusion it causes.
When is an expression unsigned? How big is the value? Does it overflow? Is the result portable, independent of the machine on which it executes?

> It also complicates the compiler; “the usual arithmetic conversions” are not easy to implement and inconsistent across architectures.

> For reasons of portability, we decided to make things clear and straightforward at the cost of some explicit conversions in the code. The definition of constants in Go—arbitrary precision values free of signedness and size annotations—ameliorates matters considerably, though.

> A related detail is that, unlike in C, int and int64 are distinct types even if int is a 64-bit type.
The int type is generic; if you care about how many bits an integer holds, Go encourages you to be explicit.

huangapple
  • 本文由 发表于 2014年6月21日 22:35:14
  • 转载请务必保留本文链接:https://go.coder-hub.com/24342617.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定