Casting usize to generic in `const fn`

#1

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: https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=c7ac7c2238ce17fd978f3f12aa3d9452

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

0 Likes

#2

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

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

0 Likes

#3

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

(or contribute!)

0 Likes

#4

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

0 Likes