Trait for 'as' casting of primitive types? (Or, type ascription of for/range)

Is there a trait bound for specifying that a generic/associated type can only be a primitive type that can be cast using the as keyword, e.g. 0_u8 as u64? Or, in my case (0 as I::UInt)..input_size.

Here's a playground link showing the issue: playground

There's num::cast::AsPrimitive.

Edit: More generally, you should probably look through num::traits if you haven't already. num::PrimInt would probably be a better choice than your custom version.

Yeah, I'm already using num_traits. Apparently I'm just wishing that we had some form of access to the compiler's secret {float} and {integer} types, yet again... But I can do what I want with I::UInt::from_u8(0)?, I guess it just feels odd to use an add-on trait/function when there's a more direct option that stops being viable just because I've switched to an associated type.

I guess a broader form of my question is, is there a better way to get the type ascription correct here:

for idx in 0..num_inputs { /* stuff */ }

where num_inputs is an I::UInt, but the type of idx seems to decide itself as an i32 in spite of num_inputs having a specified type. My current best solutions are:

for idx in (I::UInt::from(0)?)..num_inputs { /* stuff */ }

or, an extra line, but perhaps avoiding a runtime conversion step:

let input_range: Range<I::UInt> = Range { start: 0, end: num_inputs };
for idx in input_range { /* stuff */ }

Maybe this?

where T::UInt: PrimInt + Zero
    for i in T::UInt::zero()..num_inputs {

Edit: Looks like PrimInt already implies Zero through the Num trait

1 Like

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.