Evan Carroll
Evan Carroll

Reputation: 1

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

Upvotes: 3

Views: 1869

Answers (2)

Colonel Thirty Two
Colonel Thirty Two

Reputation: 26599

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 as cloning an Arc of some global default configuration.

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

Upvotes: 3

Evan Carroll
Evan Carroll

Reputation: 1

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.

Upvotes: 2

Related Questions