有没有一种方法可以让我获得一个对结构的特征实现的静态借用引用:
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`
或者,是否有一种方法可以从指向结构的全局借用静态指针获取指向特征的借用静态指针:
static instance2: &'static Example = &Example;
fn f(i: &'static Trait) {
/* ... */
}
fn main() {
// how do I invoke f passing in instance2?
}
发布于 2015-11-22 23:09:19
是的,如果特征还实现了Sync
,则可以
trait Trait: Sync {}
struct Example;
impl Trait for Example {}
static INSTANCE3: &dyn Trait = &Example;
或者声明您的特征对象也实现了Sync
trait Trait {}
struct Example;
impl Trait for Example {}
static INSTANCE3: &(dyn Trait + Sync) = &Example;
实现Sync
的类型包括
...因此在线程之间共享引用是安全的。
当编译器确定它是合适的时,就会自动实现这个特征。
确切的定义是:如果T
为Sync
,则类型&T
为Send
。换句话说,如果在线程之间传递&T
引用时不存在未定义行为(包括数据竞争)的可能性。
由于您正在共享一个引用,因此任何线程都可以调用该引用上的方法,因此您需要确保在发生这种情况时没有任何东西会违反Rust的规则。
https://stackoverflow.com/questions/19667717
复制相似问题