9

I'm looking at the numeric types in Go. I want to use uint64 literals. Is this possible in Go?

Here's an example of how I'd like to use uint64 literals:

for i := 2; i <= k; i += 1 { // I want i to be a uint64
    ...
}
  • Relevant section in the specification: [Constants](https://golang.org/ref/spec#Constants). –  Dec 19 '15 at 22:47
  • 1
    @SalvadorDali what do you mean by "put"? The answer to my original question is no, there is no such thing as a `uint64` literal in Go. You have to cast to `uint64`, apparently. –  Dec 20 '15 at 04:35

3 Answers3

18

you can just cast your integer literal to uint64.

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

Alternatively you could initialize i outside of the for loop, but then it's scoped larger than the loop itself.

var i uint64
for i = 1; i <= k; i++ {
    // note the `=` instead of the `:=`
}
// i still exists and is now k+1
Adam Smith
  • 52,157
  • 12
  • 73
  • 112
3

Let's take a look at the specification for constant: https://go.dev/ref/spec#Constants. This is what they said:

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.

And:

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.

Based on these statements and in the context of your code, the best way to initialize a variable that is not in the default type list like uint64 it to convert:

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

You have to explicitly declare your variables as that type. The int literal will be of type int https://play.golang.org/p/OgaZzmpLfB something like var i uint64 is required. In your example you'd have to change your assignment as well so something like this;

var i uint64
for i = 2; i <= k; i += 1 { // I want i to be a uint64
    ...
}
evanmcdonnal
  • 46,131
  • 16
  • 104
  • 115