有没有一种方法可以让我获取一个结构体对某个 trait 的实现的静态借用引用?
这也是可以正常工作的:
但是这样做不起作用:
trait Trait {}
struct Example;
impl Trait for Example {}
这个可以正常工作:
static instance1: Example = Example;
这也是可以正常工作的:
static instance2: &'static Example = &Example;
但是这样做不起作用:
static instance3: &'static Trait = &Example as &'static Trait;
它因此失败:
error[E0277]: the trait bound `Trait + 'static: std::marker::Sync` is not satisfied in `&'static Trait + 'static`
--> src/main.rs:10:1
|
10 | static instance3: &'static Trait = &Example as &'static Trait;
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ `Trait + 'static` cannot be shared between threads safely
|
= help: within `&'static Trait + 'static`, the trait `std::marker::Sync` is not implemented for `Trait + 'static`
= note: required because it appears within the type `&'static Trait + 'static`
= note: shared static variables must have a type that implements `Sync`
另外,是否有一种方法可以从全局借用的静态结构指针中获取到一个被借用的静态 trait 指针:
static instance2: &'static Example = &Example;
fn f(i: &'static Trait) {
/* ... */
}
fn main() {
// how do I invoke f passing in instance2?
}
as &'static T
似乎很直观,但编译器会拒绝它。可能目前还不可能实现。如果是这样,您可以通过在使用静态变量时进行强制转换来解决问题。或者,如果可能的话,使用类型参数而不是 trait 对象。在 Rust 中很少使用 trait 对象,大多数情况下类型参数会更好。 (当我开始使用 Rust 时,我经常在不必要的情况下使用 trait 对象)。例如,fn f<T: MyTrait>(i: &T) { /* ... */ }
是一个可以用任何实现了 MyTrait 的对象调用的函数。 - Zargony