我想转换&'static A
到&'static B
,其中A
是需要的性状B
(trait 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) {}
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());