无法将non-const fn`< foo称为默认值> :: default`

发布于 2025-02-03 10:06:47 字数 726 浏览 2 评论 0原文

我正在尝试创建一个我也可以借用参考的全局实例,

const GLOBAL_FOO: &Foo = &Foo::default();

impl<'a> Default for Bar<'a> {
    fn default() -> Self {
        Self { foo: GLOBAL_FOO }
    }
}

但是当我这样做时,我会遇到一个错误,

error[E0015]: cannot call non-const fn `<Foo as Default>::default` in constants
 --> src/main.rs:8:27
  |
8 | const GLOBAL_FOO: &Foo = &Foo::default();
  |                           ^^^^^^^^^^^^^^
  |
  = note: calls in constants are limited to constant functions, tuple structs and tuple variants

For more information about this error, try `rustc --explain E0015`.

我该如何在const中调用默认值来实现这一目标?

I'm trying to create a global instance that I can borrow a reference too,

const GLOBAL_FOO: &Foo = &Foo::default();

impl<'a> Default for Bar<'a> {
    fn default() -> Self {
        Self { foo: GLOBAL_FOO }
    }
}

But when I do this, I get an error,

error[E0015]: cannot call non-const fn `<Foo as Default>::default` in constants
 --> src/main.rs:8:27
  |
8 | const GLOBAL_FOO: &Foo = &Foo::default();
  |                           ^^^^^^^^^^^^^^
  |
  = note: calls in constants are limited to constant functions, tuple structs and tuple variants

For more information about this error, try `rustc --explain E0015`.

How can I work around calling default in a const to accomplish this?

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

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

发布评论

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

评论(1

捶死心动 2025-02-10 10:06:47

这里的问题是 default特征>特征default()没有> const。因此,这不是一个恒定的函数。这意味着当前从Rust 1.6开始,如果您需要常量默认您必须自己实现,

impl Foo {
  const fn new_const_default() -> Self {
    Self { ... }
  }
}

请注意,以消除冗余,可以在新的default()的顶部

impl Default for Foo {
    fn default() -> Self { Self::new_const_default() }
}

The problem here is that the Default trait declares default() without const. Thus it's not a constant function. This means that currently, as of Rust 1.6, if you need a constant Default you'll have to implement it yourself,

impl Foo {
  const fn new_const_default() -> Self {
    Self { ... }
  }
}

Note, to eliminate redundancy, you can implement Default on top of your new default(),

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