Is it possible to disable type inference in certain situations?

Viewed 195

I wrote the crate as_num which does "checked casts" between primitive numeric types. A "checked cast" is an analog to Rust's built-in checked addition. In --debug, a checked cast ensures that you can convert the result back to the original type without loss (i.e. truncation does not alter the numeric value), while in --release it should compile to a simple src as dest.

To achieve that, the crate offers a generic method as_num for primitive types that can be used to cast between types:

take_i32(2u8.as_num()); // 2 will be converted to i32 successfully
take_i8(12345u32.as_num()); // asserts at runtime since 12345 does not fit into an i8

This allows you to call as_num without stating the destination type, inferring it instead. You can explicitly state the destination type using as_num::<dest>().

When a cast is guaranteed to succeed (according to this), I would like the programmer to not have to bother with stating the destination type and let type inference do its work. If we have a (possibly) truncating cast, the programmer should be required to write the destination type.

Is this possible to achieve without resorting to two different function names, i.e. with only as_num?

0 Answers
Related