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;
}
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;
}
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.
<Foo as Default>::default in constants"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.