Why is i32::from(f) not allowed but 'f as i32' is?

The as operator, when used to convert between primitive types, is something of a brute-force tool. It mostly tries to do the "obvious" thing, at the expense of not handling edge cases well. For instance, the f32 as i32 conversion by default truncates (rounds towards zero), but what about values larger than what could fit in i32? Or NaN and infinity values? Well, right now those cases are actually not even implemented properly and cause undefined behavior!

The From and Into conversions, to the contrary, must never fail, and should also be lossless, so that if you do a roundtrip conversion, you should get back the same value as the one you started with. This means a f32-to-i32 conversion, intrinsically fallible and lossy, cannot be implemented in terms of From and Into.

1 Like