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

Viewed 119

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;
}
2 Answers

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.

There are plenty of ways to implement Default::default that are not const. For example:

use rand;

struct MyStruct {
    v: u32
}
impl Default for MyStruct {
    fn default() -> Self {
        Self {
            // RNG will never be const!
            v: rand::random()
        }
    }
}

Less contrived examples would include referencing global variables, such, cloning an Arc of some global default configuration.

Changing Deafult::default, even if supported in rustc, would be an unacceptably breaking change, and arguably undesired.

Related