为什么我得到了 "const fn中的函数指针不稳定 "的错误,但当它被包裹在一个新类型中时就消失了?

问题描述 投票:1回答:0

这是有意的行为还是编译器的错误?

以下代码无法编译。valuesMyStruct 是一个 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();
}

游乐场

rust const
© www.soinside.com 2019 - 2024. All rights reserved.