Casting usize to generic in `const fn`

So I'm playing around with const fns. I want to cast the output of std::mem::size_of::<T>() to T for all int types. In a non-const fn, I can define a casting trait and implement it for each int type (or better yet, use the num crate) - but I can't do this in a const context.

Here's a playground example of what I mean: Rust Playground

So my question is: is there any way - however hacky and terrible - to cast a usize to a generic integer type T?

1 Like

Generics with bounds can't be used in a const fn.

https://github.com/rust-lang/rust/issues/53555

I can't think of way to do it just yet, without bounds there doesn't seem to be a way to do it.

Not unlike Moore's law, I believe the simple answer here is to wait. :slight_smile:

(or contribute!)

You might also be interesting in the following discussion about core traits for these conversions:

https://github.com/rust-lang/rfcs/pull/2484