簡體   English   中英

Result<(), Box<(dyn SomeTrait + 'static)>> 不滿足 Trait Bound

[英]Trait Bound is not satisfied for Result<(), Box<(dyn SomeTrait + 'static)>>

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() ,但我想了解這里發生了什么並盡可能修復。

如果您查看unwrap方法文檔,您會發現它不是為所有Result定義的,而是只為E: Debug

impl<T, E> Result<T, E>
where
    E: Debug, 
{
    pub fn unwrap(self) -> T;
}

它需要錯誤類型E來實現Debug以便在解包失敗時可以打印錯誤。

錯誤消息顯示結果類型為Result<(), Box<(dyn SomeTrait + 'static)>> ,所以E = Box<(dyn SomeTrait + 'static)> 您可以通過SomeTrait: Debug使此錯誤類型可SomeTrait: Debug ,這要求實現SomeTrait任何類型也必須實現Debug

pub trait SomeTrait: Debug {}

#[derive(Debug)]
pub struct Impl1 {}

執行此操作后,您將遇到下一個錯誤:

error[E0277]: `dyn SomeTrait` cannot be shared between threads safely
  --> src/main.rs:11:1
   |
11 | pub static GLOBAL_THING: OnceCell<Box<dyn SomeTrait>> = OnceCell::new();
   | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ `dyn SomeTrait` cannot be shared between threads safely
   |
   = help: the trait `Sync` is not implemented for `dyn SomeTrait`
   = note: required because of the requirements on the impl of `Sync` for `Unique<dyn SomeTrait>`
   = note: required because it appears within the type `Box<dyn SomeTrait>`
   = note: required because of the requirements on the impl of `Sync` for `once_cell::imp::OnceCell<Box<dyn SomeTrait>>`
   = note: required because it appears within the type `once_cell::sync::OnceCell<Box<dyn SomeTrait>>`
   = note: shared static variables must have a type that implements `Sync`

要解決此問題,您還需要使裝箱的 trait 對象Send + Sync以便它可以跨線程共享。

pub static GLOBAL_THING: OnceCell<Box<dyn SomeTrait + Send + Sync>> = OnceCell::new();

您可以在Playground上看到最終結果。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM