为什么是default :: default()一个常数函数?

发布于 2025-02-03 18:40:55 字数 431 浏览 1 评论 0原文

从生锈1.6开始,当前特征 default 被定义为,

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

为什么这不是

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

太阳哥哥 2025-02-10 18:40:55

有很多方法可以实现默认:: 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克隆。

更改默认值::默认即使在Rustc中支持,也是不可接受的变化,并且可以说是不希望的。

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.

古镇旧梦 2025-02-10 18:40:55

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 。当可以声明const中的功能时,也许可以更好地解决此问题。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文