2

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;
}
Evan Carroll
  • 78,363
  • 46
  • 261
  • 468
  • 1
    `Default` is older than `const fn`, isn't it? Changing it would be a breaking change if every implementation would then have to be `const`. – Sebastian Redl Jun 01 '22 at 20:54
  • @SebastianRedl it's certainly older than constant functions traits which don't exist yet. But all things are on the table for Rust 2.0. ;) – Evan Carroll Jun 01 '22 at 20:55
  • 3
    Is it guaranteed to be always `const`able, however? Allocations in `const fn` are unstable too, for example, so ` as Default>::default` (which is available when `T: Default`) will not yet be `const`. – Cerberus Jun 02 '22 at 02:52

2 Answers2

3

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.

Colonel Thirty Two
  • 23,953
  • 8
  • 45
  • 85
2

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.

Evan Carroll
  • 78,363
  • 46
  • 261
  • 468
  • The issue you linked is a wrong one. The right issue is probably https://github.com/rust-lang/rust/issues/67792, although we're not sure this is the way forward. Probably the working solution will be some kind of an effect system, currently in planning stage. – Chayim Friedman Aug 28 '23 at 22:02