【发布时间】:2021-12-04 02:44:37
【问题描述】:
use once_cell::sync::OnceCell;
pub trait SomeTrait {}
pub struct Impl1 {}
impl SomeTrait for Impl1 {}
pub static GLOBAL_THING: OnceCell<Box<dyn SomeTrait>> = OnceCell::new();
pub fn main() {
GLOBAL_THING.set(Box::new(Impl1 {})).unwrap();
}
我收到此错误,不知道如何解释或修复它。
error[E0599]: the method `unwrap` exists for enum `Result<(), Box<(dyn SomeTrait + 'static)>>`, but its trait bounds were not satisfied
--> src/main.rs:11:42
|
11 | GLOBAL_THING.set(Box::new(Impl1 {})).unwrap();
| ^^^^^^ method cannot be called on `Result<(), Box<(dyn SomeTrait + 'static)>>` due to unsatisfied trait bounds
|
= note: the following trait bounds were not satisfied:
`Box<dyn SomeTrait>: Debug`
一个简单的解决方法是只使用if let Err() = GLOBAL_THING.set() {panic!(...)} 而不是使用unwrap(),但我想了解这里发生了什么并尽可能修复。
【问题讨论】:
标签: rust traits abstraction dynamic-dispatch