Generic numerical constants in stable Rust

What is the best way, in stable Rust in October 2022, to write code that is generic over numerical types and contains some arbitrary numerical constants?

Trivial (perhaps excessively so) example: How do I replace the following definitions with a single generic one?

fn add_42_u32(n: u32) -> u32 { n + 42 }
fn add_42_u64(n: u62) -> u64 { n + 42 }
fn add_42_i32(n: i32) -> i32 { n + 42 }

Can I do better than?

fn add_42<T: Add<Output = T> + From<u8>>(n: T) -> T { n + 42.into() }

Use num_traits. You can use PrimInt trait.

3 Likes

If you want to stick to the standard library, note that T: From<u8> doesn't include i8, so you may want TryFrom<u8> instead. That will still be infallible for all those that do have From<u8>, and the optimizer should be able to cut out the error path for i8 if you're using small enough constants.

1 Like