Go 中有 uint64 字面量吗?

Are there uint64 literals in Go?

我正在查看 Go 中的 numeric types。我想使用 uint64 文字。这在 Go 中可能吗?

这是我想如何使用 uint64 文字的示例:

for i := 2; i <= k; i += 1 { // I want i to be a uint64
    ...
}

您可以将整数文字转换为 uint64

for i := uint64(1); i <= k; i++ {
    // do something
}

或者,您可以在 for 循环之外初始化 i,但它的范围大于循环本身。

var i uint64
for i = 1; i <= k; i++ {
    // note the `=` instead of the `:=`
}
// i still exists and is now k+1

您必须将您的变量显式声明为该类型。 int 文字将是 int https://play.golang.org/p/OgaZzmpLfB 类型的 var i uint64 是必需的。在您的示例中,您还必须更改您的分配,因此类似这样;

var i uint64
for i = 2; i <= k; i += 1 { // I want i to be a uint64
    ...
}

让我们看一下常量的规范:https://go.dev/ref/spec#Constants。他们是这样说的:

A constant may be given a type explicitly by a constant declaration or conversion, or implicitly when used in a variable declaration or an assignment or as an operand in an expression.

并且:

An untyped constant has a default type which is the type to which the constant is implicitly converted in contexts where a typed value is required, for instance, in a short variable declaration such as i := 0 where there is no explicit type. The default type of an untyped constant is bool, rune, int, float64, complex128 or string respectively, depending on whether it is a boolean, rune, integer, floating-point, complex, or string constant.

根据这些语句并在您的代码上下文中,初始化不在默认类型列表中的变量的最佳方法 uint64 将其转换为:

for i := uint64(2); i <= k; i++ {
  ...
}