Rust 常量表达式可以使用像 Default 这样的特征吗?
Can Rust constant expressions use traits like Default?
这段代码报错:
#[derive(Default)]
struct A {
b: Option<()>,
c: Option<()>,
}
const a: A = A {
b: None,
..Default::default()
};
error[E0015]: calls in constants are limited to constant functions, tuple structs and tuple variants
--> src/lib.rs:9:7
|
9 | ..Default::default()
| ^^^^^^^^^^^^^^^^^^
在这个小例子中,这不是一个大问题,但如果我有一个由多个实现 Default
特性的结构组成的结构,则无法使用它至少会带来不便。
虽然我可以写这个,但它没有 Default
提供的灵活性:
impl A {
const fn new(b: Option<()>) -> Self {
A { b, c: None }
}
}
const a: A = A::new(None);
有什么办法可以避免这样做吗?
不,不可能在常量上下文中使用特征。这仍在 RFC #2632 — Calling methods on generic parameters of const fns 中讨论。
另请参阅:
..Default::default()
语法不限于 Default::default()
,因此您可以编写一个 const fn
类默认函数并在常量内部使用它:
struct A {
b: Option<()>,
c: Option<()>,
}
impl A {
const fn new() -> A {
A {
b: None,
c: None,
}
}
}
impl Default for A {
fn default() -> A {
// implementing using new() instead of #[derive]
// to avoid diverging implementations
A::new()
}
}
const a: A = A {
b: None,
..A::new()
};
这段代码报错:
#[derive(Default)]
struct A {
b: Option<()>,
c: Option<()>,
}
const a: A = A {
b: None,
..Default::default()
};
error[E0015]: calls in constants are limited to constant functions, tuple structs and tuple variants
--> src/lib.rs:9:7
|
9 | ..Default::default()
| ^^^^^^^^^^^^^^^^^^
在这个小例子中,这不是一个大问题,但如果我有一个由多个实现 Default
特性的结构组成的结构,则无法使用它至少会带来不便。
虽然我可以写这个,但它没有 Default
提供的灵活性:
impl A {
const fn new(b: Option<()>) -> Self {
A { b, c: None }
}
}
const a: A = A::new(None);
有什么办法可以避免这样做吗?
不,不可能在常量上下文中使用特征。这仍在 RFC #2632 — Calling methods on generic parameters of const fns 中讨论。
另请参阅:
..Default::default()
语法不限于 Default::default()
,因此您可以编写一个 const fn
类默认函数并在常量内部使用它:
struct A {
b: Option<()>,
c: Option<()>,
}
impl A {
const fn new() -> A {
A {
b: None,
c: None,
}
}
}
impl Default for A {
fn default() -> A {
// implementing using new() instead of #[derive]
// to avoid diverging implementations
A::new()
}
}
const a: A = A {
b: None,
..A::new()
};