Coercing generic uint

I have a generic method

fn x<I>(&mut self, index: I) -> SomeXtype 
    where I : SomeUInt  // ...which bounds from `num` or `num-traits` here?
   self.myvec.get(index as usize).unwrap()

where self.myvec is a Vec<SomeXtype>. Which trait bound should I use to make index as usize or usize::from::<T>(index) work? Thanks.

You can add where I: num_traits::NumCast, and use num_traits::cast to do the conversion.

Or you can use the similar bound where I: TryInto<usize>.

usize::from(index) will work if you add where usize: From<I>, but this is not as useful as one might hope. This bound isn't satisfied for u32 or u64, because it is only implemented for conversions that never fail, even on 16-bit architectures.

index as usize isn't possible in generic code, because there is no trait for as casts.

There's also AsPrimitive, but I would rather recommend using one the checked methods.


This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.