Search code examples
rustsyntaxconstantstraits

What is "impl const" in Rust?


I see this a lot in Rust code. Here are a few examples from the standard library:

impl<T> const Default for Option<T> {...}

impl const From<char> for u64 {...}

What is impl const?


Solution

  • If you run the code:

    trait Example {}
    impl const Example for u8 {}
    

    You get an error message that points you in the right direction:

    error[E0658]: const trait impls are experimental
     --> src/lib.rs:3:6
      |
    3 | impl const Example for u8 {}
      |      ^^^^^
      |
      = note: see issue #67792 <https://github.com/rust-lang/rust/issues/67792> for more information
      = help: add `#![feature(const_trait_impl)]` to the crate attributes to enable
    

    Issue 67792 is the tracking issue for RFC 2632 — Calling methods on generic parameters of const fns.

    This is an unstable syntax that allows defining traits that can be used in a const context. It's paired with the equally unstable ~const syntax that can be used in trait bounds:

    // 1.59.0-nightly (2021-12-20 23f69235ad2eb9b44ac1)
    #![feature(const_fn_trait_bound)]
    #![feature(const_trait_impl)]
    
    trait Example {
        fn usage(&self) -> Self;
    }
    
    impl const Example for u8 {
        fn usage(&self) -> Self {
            42
        }
    }
    
    const fn demo<T: ~const Example>(v: &T) -> T {
        v.usage()
    }
    
    const VALUE: u8 = demo(&1);
    
    fn main() {
        dbg!(VALUE);
    }