在 const 函数中如何处理 trait 对象?

问题描述

我试图创建一个包裹在 MaybeUninit 中的未初始化的盒装特征对象。

trait Foo {}

const fn test() {
    // Error!
    let _bar: MaybeUninit<Box<dyn Foo>> = MaybeUninit::uninit();
}

playground link

编译器给了我以下错误

error[E0723]: trait bounds other than `Sized` on const fn parameters are unstable

我不明白为什么编译器会谈论 trait bound,因为我的函数没有任何泛型参数。

我找到了解决方法,只需将 Box<dyn Foo> 包装到另一个结构中即可。

trait Foo {}

struct BoxedFoo(Box<dyn Foo>);

const fn test() {
    // It works!
    let _bar: MaybeUninit<BoxedFoo> = MaybeUninit::uninit();
}

它有效。

为什么包装盒子会有什么不同?第一种情况与 trait bound 有什么关系,而与第二种情况无关?

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)