How to use the unstable const trait feature?

Hello, basically, I want to do that:

#![feature(const_trait_impl)]

#[const_trait]
trait ConstInto<T> {
    fn into_(self) -> T;
}

impl const ConstInto<u32> for i32 {
    fn into_(self) -> u32 {
        self as u32
    }
}

const X: u32 = 123_i32.into_();

playground link

The way this feature is used has moved a lot recently, and I can't get it to compile. How can I do that?

Currently, it's not a good idea to use const Trait, because the code related is removed and the design is immature.

Bummer. I'm writing a firmware, and I have to constify a bunch of data to put in on the flash memory. I need some kind of const traits to be able to write the data in a concise manner...

Not having traits is like fighting with the arms attached in the back.

Is is something actively worked on? I really need this feature, so as I see things, I can go 2 paths:

  • Either I wait for the feature to be available before writing this part of my code (I can wait for a few week, it's just a personal project);
  • Or I pin my compiler to an old version, and when the feature is available, I use the newest compiler and I update my traits to match the new syntax.

It is still being actively worked on as far as I understand, but we're not talking weeks before stabilization. More like years.

I am fine using the nightly compiler. As long as I can use my traits in a const context, I'm fine with it. So any semi-usable nightly implementation is good enough. How long before that, in your opinion?

Do read the linked issue.

For temporary preview of the effects rewrite, add feature(effects) to your crate code. Most bugs/misbehaviors are known so consider opening a thread on the const-eval stream on Zulip before opening an issue.

I.e. your code compiles with #![feature(const_trait_impl, effects)]. Rust Playground

1 Like

Oh, nice, that's all I was asking for. Thank you.

Looks like you got it working but I'll mention an alternative approach anyways in case it may be helpful or at least interesting. I don't know what your project specifically is but in case you find its helpful there's this cool blog posts / crate: So Zero It's ... Negative? (Zero-Copy #3) - In Pursuit of Laziness. The idea there is that it's macro that bakes the content of a JSON file into the binary, in the form of pre-deserialized constants and structs (rather than merely baking in a JSON string that the program has to deserialize). If you combined this with a build.rs file that implemented whatever logic you need to generate the data into the JSON file, you might be able to do some helpful things.

1 Like

Thanks, I have thought about something like that, but instead I might create a simple web app generating a rust file. There is a lot of behavior to configure in my program, so it's easier for the user that way.

1 Like