I am porting an int-set type to generics. It holds bits in a block structure with 512 bits per block. At some point, I need to divide by 512:
func block[T constraints.Integer](i T) T {
return i / 512
}
Go 1.18 beta 2 complains: cannot convert 512 (untyped int constant) to T
The problem is that uint8 and int8 cannot represent the number 512. If I build a constraint similar to constraints.Integer that excludes ~uint8 and ~int8, it works fine. Explicit casting is no better, and there is no promotion (e.g., cast i to int and cast the result back to T) that's suitable for all integer types. I would like to shrink the block size for (u)int8, but there's no way to specialize the logic for specific types.
I figured out that I can use i >> 9 instead of i / 512 in this instance, though there will be other cases (divide by non-Po2) where there isn't a simple workaround Is there a general way around this limitation?