有没有办法让我获得一个结构的特征实现的静态借用引用:
trait Trait {}
struct Example;
impl Trait for Example {}
Run Code Online (Sandbox Code Playgroud)
这很好用:
static instance1: Example = Example;
Run Code Online (Sandbox Code Playgroud)
这也很好:
static instance2: &'static Example = &Example;
Run Code Online (Sandbox Code Playgroud)
但这不起作用:
static instance3: &'static Trait = &Example as &'static Trait;
Run Code Online (Sandbox Code Playgroud)
它失败了:
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`
Run Code Online (Sandbox Code Playgroud)
或者,有没有办法从全局借用的静态指针获取到特征的借用静态指针:
static instance2: &'static Example = &Example;
fn f(i: &'static Trait) {
/* ... */
}
fn main() {
// how do I invoke f passing in instance2?
}
Run Code Online (Sandbox Code Playgroud)
是的,你可以,如果trait 也实现了Sync:
trait Trait: Sync {}
struct Example;
impl Trait for Example {}
static INSTANCE3: &dyn Trait = &Example;
Run Code Online (Sandbox Code Playgroud)
或者,如果您声明您的 trait 对象还实现了Sync:
trait Trait {}
struct Example;
impl Trait for Example {}
static INSTANCE3: &(dyn Trait + Sync) = &Example;
Run Code Online (Sandbox Code Playgroud)
实现的类型Sync是那些
[...] 在线程之间共享引用是安全的。
当编译器确定它合适时,这个特性会自动实现。
精确的定义是:一种类型
T是Sync,如果&T是Send。换句话说,如果&T在线程之间传递引用时不存在未定义行为(包括数据竞争)的可能性。
由于您正在共享一个引用,因此任何线程都可以调用该引用上的方法,因此您需要确保在发生这种情况时不会违反 Rust 的规则。