8

I am currently doing the Go Lang tutorial, "Numeric Constants" to be precise. The example code starts with the following statement:

const (
    // Create a huge number by shifting a 1 bit left 100 places.
    // In other words, the binary number that is 1 followed by 100 zeroes.
    Big = 1 << 100
    // Shift it right again 99 places, so we end up with 1<<1, or 2.
    Small = Big >> 99
)

The constant Big is obviously huge, and I am trying to print it and its type, like this:

fmt.Printf("%T", Big)
fmt.Println(Big)

However, I get the following error for both lines:

# command-line-arguments ./compile26.go:19: constant 1267650600228229401496703205376 overflows int

I would try casting Big to some other type, such as uint64, which it overflowed with the same error, or just convert it to a string, but when trying Big.String() I get the following error:

Big.String undefined (type int has no field or method String)

It appears that its type is int, yet I can't print it or cast it to anything and it overflows all methods. What do I do with this number/object and how do I print it?

arik
  • 28,170
  • 36
  • 100
  • 156
  • 5
    Const in Go are _not_ normal variables which happen to be be const, they are different. The concept of a const exists during compilation only, const are of arbitrary (almost) precision and size and arithmetic is possible. When _using_ a const it is converted to a "proper" type. This conversion may fail as in your case in which aour program is malformed. There is no (direct, simple) way to print `Big`. – Volker Oct 10 '16 at 21:50
  • 1
    Possible duplicate of [How does Go perform arithmetic on constants?](http://stackoverflow.com/questions/38982278/how-does-go-perform-arithmetic-on-constants) – icza Oct 10 '16 at 22:23
  • @Volker @arik it seems you can print it if you explicitly type the const as a float64 or a complex128. Is the value of `Big` as a float64, then, different than the value of the implicitly typed `Big` that would get converted to aproper type at runtime when it is used? `const Big float64 = 1 << 100` `fmt.Printf("Type of Big is: %T, Value of Big is %v", Big, Big)` This prints "Type of Big is: float64, Value of Big is 1.2676506002282294e+30" – no_stack_dub_sack Aug 12 '21 at 15:25

1 Answers1

1

That value is larger than any 64 bit numeric type can hold, so you have no way of manipulating it directly.

If you need to write a numeric constant that can only be manipulated with the math/big package, you need to store it serialized in a format that package can consume. Easiest way is probably to use a base 10 string:

https://play.golang.org/p/Mzwox3I2SL

bigNum := "1267650600228229401496703205376"
b, ok := big.NewInt(0).SetString(bigNum, 10)
fmt.Println(ok, b)
// true 1267650600228229401496703205376
JimB
  • 104,193
  • 13
  • 262
  • 255