Clean way to have a function accept u16 and usize, including unconstrained small positive integer literals

Viewed 105

I'd like to have a function accept both u16 and usize, and be able to call it those ways:

usu(1 as usize);           // 1
usu([1,2].len());          // 2
usu(3u16);                 // 3
let u16 = 4u16; usu(u16);  // 4
usu(5);                    // 5

Defining the usu function as fn usu<U: Into<usize>>(u: U) { doesn't work for test case 5 because 5, being an unconstrained literal, is interpreted as i32 by the compiler.

I don't want to use unsafe or have an added runtime cost, nor do I want users of my crate to use macros, import traits, or constrain their literals, just to use the usu function.

Is there a reasonable way to make usu accept both u16 and usize (Rust edition 2021) ?

test playground

0 Answers
Related