这是有意的行为还是编译器的错误?
以下代码无法编译。values
在 MyStruct
是一个 Option
自从 Vec::new
不是一个const fn - 而是 Option::None
是常数(但它仍然不能编译)。
type MyFun = fn(input: u32) -> u32;
struct MyStruct {
values: Option<Vec<MyFun>>,
}
impl MyStruct {
pub const fn init() -> Self {
Self { values: None }
}
}
fn main() {
MyStruct::init();
}
error[E0723]: function pointers in const fn are unstable
--> src/main.rs:9:24
|
9 | Self { values: None }
| ^^^^
|
= note: see issue #57563 <https://github.com/rust-lang/rust/issues/57563> for more information
= help: add `#![feature(const_fn)]` to the crate attributes to enable
使用一个新类型(Wrapped
)解决了这个问题。这感觉很奇怪,因为两个例子都是一样的(至少生成的二进制文件应该是一样的)。这种行为是有意为之还是BUG?
这很有效
type MyFun = fn(input: u32) -> u32;
struct Wrapped(Vec<MyFun>);
struct MyStruct {
values: Option<Wrapped>,
}
impl MyStruct {
pub const fn init() -> Self {
Self { values: None }
}
}
fn main() {
MyStruct::init();
}