Quantcast
Channel: Recent Questions - Stack Overflow
Viewing all articles
Browse latest Browse all 12111

Making widening integer conversions safely

$
0
0

I need to make a few safe widening integer conversions –uint32 to uint and uint to uint64, for example. I know it’s possible to achieve this with an explicit type conversion:

x := uint32(1) // supposey := uint(x)

But if x’s type changes later on, this will keep compiling while now doing the wrong thing.

x := int32(-1)y := uint(x) // y is now 4294967295 or 18446744073709551615
x := uint64(4294967296)y := uint(x) // y is now zero if uint is 32 bits

Is there an idiomatic way to perform an integer conversion that must either preserve the original value or fail to compile? The best I can come up with is to have a package of functions like this, which doesn’t seem worth it:

func Uint32ToUint(x uint32) uint {    return uint(x)}

Viewing all articles
Browse latest Browse all 12111

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>