Fast generic conversion from usize to u32

⚓ Rust    📅 2025-07-13    👤 surdeus    👁️ 2      

surdeus

How does one create a version of my_fun below with prototype

fn my_generic<U>(index : usize) -> U

The index keeps increasing for a huge number of conversions and validity
of the conversions should be checked at the end (not for each conversion).

fn my_fn(index : usize) -> u32 {  
   index as u32 
}

fn my_generic< U : From<usize> >(index : usize) -> U {  
   index.into()
}

fn main()
{  let index         : usize = 5;
   let index_fn      : u32   = my_fn(index);
   let index_generic : usize = my_generic(index);
   println!( "index_fn = {index_fn}" );
   println!( "index_generic = {index_generic}" );
   //
   // If you uncomment the statement below you get the error
   // the trait From<usize> is not implemented for u32.
   // let index_generic : u32 = my_generic(index);
}
/* 
// The following function results in the compiler error below it.
fn my_generic<U>(index : usize) -> U {  
   index as U 
}
an as expression can only be used to convert between primitive types ..
*/

8 posts - 3 participants

Read full topic

🏷️ rust_feed