我可以有一个对 trait 对象的静态借用引用吗? [英] Can I have a static borrowed reference to a trait object?

查看:30
本文介绍了我可以有一个对 trait 对象的静态借用引用吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法让我获得对结构的 trait 实现的静态借用引用:

Is there a way for me to obtain a static borrowed reference to a struct's implementation of a 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`

或者,有没有办法从指向结构的全局借用静态指针中获取指向特征的借用静态指针:

Alternatively, is there a way to obtain a borrowed static pointer to a trait from a global borrowed static pointer to a struct:

static instance2: &'static Example = &Example;

fn f(i: &'static Trait) {
    /* ... */
}

fn main() {
    // how do I invoke f passing in instance2?
}

推荐答案

是的,你可以,如果 trait 也实现了 同步:

Yes, you can, if the trait also implements Sync:

trait Trait: Sync {}

struct Example;
impl Trait for Example {}

static INSTANCE3: &dyn Trait = &Example;

或者如果你声明你的特征对象实现了Sync:

Or if you declare that your trait object also implements Sync:

trait Trait {}

struct Example;
impl Trait for Example {}

static INSTANCE3: &(dyn Trait + Sync) = &Example;

实现Sync的类型是那些

[...] 在线程之间共享引用是安全的.

[...] for which it is safe to share references between threads.

当编译器确定它合适时,这个特性会自动实现.

This trait is automatically implemented when the compiler determines it's appropriate.

准确的定义是:如果&TSend,类型T 就是Sync.换句话说,如果在线程之间传递 &T 引用时不存在未定义行为(包括数据竞争)的可能性.

The precise definition is: a type T is Sync if &T is Send. In other words, if there is no possibility of undefined behavior (including data races) when passing &T references between threads.

由于您共享一个引用,因此任何线程都可以调用该引用上的方法,因此您需要确保如果发生这种情况,不会违反 Rust 的规则.

Since you are sharing a reference, any thread would be able to call methods on that reference, so you need to ensure that nothing would violate Rust's rules if that happens.

这篇关于我可以有一个对 trait 对象的静态借用引用吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆