无法将non-const fn`< foo称为默认值> :: default`
我正在尝试创建一个我也可以借用参考的全局实例,
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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这里的问题是
default
特征>特征default()
没有> const
。因此,这不是一个恒定的函数。这意味着当前从Rust 1.6开始,如果您需要常量
默认
您必须自己实现,请注意,以消除冗余,可以在新的
default()
的顶部The problem here is that the
Default
trait declaresdefault()
withoutconst
. Thus it's not a constant function. This means that currently, as of Rust 1.6, if you need a constantDefault
you'll have to implement it yourself,Note, to eliminate redundancy, you can implement
Default
on top of your newdefault()
,