A generic argument in a function which can be typecasted to usize

I have a function which takes a generic argument and somewhere in the middle of the program that generic argument is typecasted to usize (using as) and used as an index to type [&str].
I wanted to know any trait exists by which I can bound my generic type to mark it as convertible to usize.

Note: typecasting to usize was required because earlier my code was failing with below error

the type `[&str]` cannot be indexed by `u8`
the trait `SliceIndex<[&str]>` is not implemented for `u8`

No, unfortunately conversions to usize are lacking in the standard library. For u8 there is From/Into, but notably it's lacking for u32 and u64. The best you could do is TryFrom and unwrap it.

You'll need a custom trait. num-traits has a few, e.g. ToPrimitive:

I'm unclear on the goal here. For example, -1_i8 as usize will compile, but feels like it probably not something that makes sense to allow for indexing.

You could consider where T: TryInto<usize>, and use a[x.try_into().unwrap()] for indexing? But my inclination would probably just just make your caller give you a usize.

Why not express your goal directly as a generic bound? If you want to index a slice, then just put the SliceIndex bound on your index type. First of all, that makes more sense to the reader/caller than arbitrary conversions for who-knows-what-reason. Second, it also lets the caller index using types other than usize, eg. ranges.

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.