I am working on a project which should be available as either 64bit or 32bit.
Due to 3rd party driver, I am forced to work with int, rather than int64.
const (
_ = iota // ignore zero iota
KiB = 1 << (10 * iota)
MiB
GiB
TiB
)
func doSomething() (ok bool) {
if strconv.IntSize != 64 {
// exiting early from function because default int is not 64bit.
return false
}
ThirdPartyDriverBytes = 5 * GiB
return true
}
Unfortunately the compiler complains, I get a constant 5368709120 overflows int
error.
How can I effectively work around this issue? Is there a way I can force this 5 * GiB calculation to occur at runtime?
I have found a workaround... 5 * GiB
is a constant expression, so gets computed by the compiler.
By splitting up into multiple statements, it no longer happens.
defaultBytes := 5
ThirdPartyDriverBytes = defaultBytes * GiB
Just explicitly type the variable to int64
instead of the platform-dependent int
:
var ThirdPartyDriverBytes int64
const (
_ int64 = iota // ignore zero iota
KiB = 1 << (10 * iota)
MiB
GiB
TiB
)
This is clearer than trying to work around the compiler inferring types from constant expressions.