1

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.

paddy
  • 60,864
  • 6
  • 61
  • 103
  • 2
    The grammar does not indicate that integer literals can contain a type suffix, so as a result you would need to assign or cast to the desired type: https://go.dev/ref/spec#Integer_literals – paddy Mar 20 '23 at 03:28
  • 1
    Related: https://stackoverflow.com/questions/34376141/are-there-uint64-literals-in-go – paddy Mar 20 '23 at 03:29
  • Hi @paddy, I found this post on [tutorialspoint](https://www.tutorialspoint.com/go/go_constants.htm) website but this really doesn't work (I just tested [this](https://go.dev/play/p/JKCbUv4pHUD) code on go playground right now). In fact, go official docs doesn't have any mention about literal suffix. :( – Matheus Sousa Mar 20 '23 at 04:47
  • 3
    Well, that's not what the language specification says. You might want to write to tutorialspoint and point out the error. Personally, I wouldn't bother with that website at all. – paddy Mar 20 '23 at 05:05

1 Answers1

6

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)
Burak Serdar
  • 46,455
  • 3
  • 40
  • 59