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) // suppose
y := 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)
}
I don't know of a very clean approach, but if there potentially a bunch of different types that you want to allow to be cast to
uint, then instead of defining a separate function for each such cast, another option is to define an interface with the appropriate set of types, and then define a generic function that's defined only for types in that set:[playground link]