为什么 Default::d efault() 不是常量函数?



在Rust 1.6中,当前特性Default定义为,

pub trait Default {
fn default() -> Self;
}

为什么这不是

pub trait Default {
const fn default() -> Self;
}

有很多方法可以实现Default::default而不是const。例如:

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

不那么做作的例子包括引用全局变量,例如克隆一些全局默认配置的Arc

更改Default::default,即使在rustc中支持,也将是一个不可接受的破坏性更改,并且可以说是不希望的。

rustc的硬性限制

这是因为目前

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

这正在GitHub #63065上工作。如果trait中的函数可以声明为const,可能会有更好的解决方案。

  • 如果你想知道如何解决这个问题,现在看看问题的答案"Rust:不能在constants">
  • 中调用非常量fn<Foo as Default>::default

最新更新