Const from (filler for silly 15 characters lower title limit)

Sometimes I’d like to write code like this:

fn main() {
    const N: u8 = 5;
    const M: usize = usize::from(N);
    let a = [0; M];
}

For this to work, I believe usize::from would need to be a const function, but there’s two problems with that:

  1. Const functions aren’t stable yet.
  2. More critically, the RFC for const functions specifically mentions that trait methods/implementations can’t be const in the current design. That seems like it’d rule out being able to use From::from, unless something has changed since the RFC or I’ve misinterpreted the text.

Not sure if there’s a way to do what you’re trying to do here, I’m afraid :frowning:

3 Likes

Well in that particular case you can use N as usize instead of from. But that only works with primitives.

More generally the only current alternative I can think of is to use a build script to generate constants. Which can be a bit like using a sledgehammer to crack a nut.

1 Like