锈静态特征转换

时间:2019-02-01 21:35:24

标签: casting rust

我想转换&'static A&'static B,其中A是需要的性状Btrait A: B {})。

#![allow(unused)]

pub trait B {}

pub trait A: B {}

pub struct C(i32);

impl A for C {}
impl B for C {}

static mut GLOBAL: &'static A = &C(6);

fn get() -> &'static A {
    unsafe {
        if
        /* Checks that it has been initialized (threadsafe) */
        false {
            // Return empty placeholder (zero-sized in acctual version)
            static TMP: C = C(0);
            &TMP
        } else {
            GLOBAL
        }
    }
}

fn main() {
    use_static_ref(get());
}

// In library
fn use_static_ref(reference: &'static B) {}

Rust Playground

error[E0308]: mismatched types
  --> src/main.rs:29:20
   |
29 |     use_static_ref(get());
   |                    ^^^^^ expected trait `B`, found trait `A`
   |
   = note: expected type `&'static (dyn B + 'static)`
              found type `&'static (dyn A + 'static)`

我不知道是否有帮助,但是从这一步开始工作可能会更容易。

let boxed = Box::new(C::new());

// Something could go in here maybe?

// Consumes to set static reference which is retrieved by `get()`.
set_global(boxed);

// Attempt to use static reference as B, but fails.
requires_B(get());

0 个答案:

没有答案