Search code examples
rustdefault

Why isn't Default::default() a constant function?


As of Rust 1.6, the current trait Default is defined as,

pub trait Default {
    fn default() -> Self;
}

Why isn't this though

pub trait Default {
    const fn default() -> Self;
}

Solution

  • Hard limitation of rustc

    This is because currently,

    error[E0379]: functions in traits cannot be declared const
      --> src/main.rs:15:2
       |
    15 |     const fn default() -> Self {
       |     ^^^^^ functions in traits cannot be const
    

    This is being worked on GitHub #63065. Perhaps there will be a better solution to this problem when functions in traits can be declared const.