Are there uint64 literals in Go?
Asked Answered
O

3

12

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
    ...
}
Oubre answered 19/12, 2015 at 22:41 Comment(2)
Relevant section in the specification: Constants.Manners
@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.Oubre
D
19

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
Disesteem answered 19/12, 2015 at 22:43 Comment(0)
N
4

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++ {
  ...
}
Northington answered 19/1, 2022 at 10:10 Comment(1)
Great answer with references to the documentation.Alive
A
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
    ...
}
Amyl answered 19/12, 2015 at 22:45 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.