英文:
Type inference for numbers in Go
问题
我需要了解如何在Go语言中推断数字类型。
在C++中,我可以这样做:
auto number = 0LL
这样,g++就知道number是一个long long int
变量。
我想强调一下数字类型!Go语言默认使用int
类型(int
是根据机器架构而定的int32
或int64
)。
是否存在一种方式,可以在不像上面的代码那样显式声明的情况下,使用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)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论