Go中的数字类型推断

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

Type inference for numbers in Go

问题

我需要了解如何在Go语言中推断数字类型。

在C++中,我可以这样做:

auto number = 0LL

这样,g++就知道number是一个long long int变量。

我想强调一下数字类型!Go语言默认使用int类型(int是根据机器架构而定的int32int64)。

是否存在一种方式,可以在不像上面的代码那样显式声明的情况下,使用uint32或任何其他数字类型来定义变量?具体来说,是否可以使用:=构造函数?

注意:我不知道如何在C++中调用这个操作,所以我也不知道如何在Go语言中搜索相关信息。

英文:

I need to know about how I can infer a number type in Go.

In C++, I can do something like this:

auto number = 0LL

With this, the g++ knows that number is a long long int variable.

I want to emphasis the number type here! Go uses int as default type (int is int32 or int64 depending on machine architecture).

Exists any way that I can define a variable with uint32 or any other number type without declaring explicitly like in the code above? More specifically, using the := constructor?

Obs: I don't know how to call this operation in C++ so I don't know how to search about it in Go.

答案1

得分: 6

在Go语言中,未指定类型的字面量会根据上下文进行解释。如果你将一个未指定类型的数值字面量赋值给一个uint32类型的变量,该字面量会被转换为uint32类型。对于短声明,声明的变量类型也会根据上下文确定,你必须显式地指定类型:

x := uint32(123)

这等同于

var x uint32 = 123

或者

var x = uint32(123)
英文:

In Go, untyped literals are interpreted based on context. If you assign an untyped numeric literal to, say, a uint32 value, that literal is converted to uint32. For short declarations, the declared variable type is determined based on context as well, you have to specify the type explicitly:

x:=uint32(123)

which is equivalent to

var x uint32 = 123

or

var x = uint32(123)

huangapple
  • 本文由 发表于 2023年3月20日 10:51:10
  • 转载请务必保留本文链接:https://go.coder-hub.com/75786229.html
匿名

发表评论

匿名网友

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

确定