I try to implement a function foo() -> u8
for bitoperations.
Therefore I wrote:
let v: u16 = 454545;
v & 0b111
Note that the last operation will limit the values to something narrower (3) than 8 bits.
Also both values in the last operation are unsigned
.
Also, the narrowing bits are const
and thus can be determined at compile time.
Rust complains:
error[E0308]: mismatched types
| let v: u16 = 454545;
| v & 0b111
| ^^^^^^^^^ expected `u8`, found `u16`
|
help: you can convert a `u16` to a `u8` and panic if the converted value doesn't fit
|
| (v & 0b111).try_into().unwrap()
| + +++++++++++++++++++++
It would be great IMO if Rust could infer from the operation, that this bit and is safe and thus does a auto-convert. Not sure whether this also could apply to other scenarios.