Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

rust

default

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;
}
like image 521
NO WAR WITH RUSSIA Avatar asked Oct 19 '25 02:10

NO WAR WITH RUSSIA


1 Answers

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.

like image 186
Colonel Thirty Two Avatar answered Oct 20 '25 17:10

Colonel Thirty Two



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!