首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >我可以有一个对特征对象的静态借用引用吗?

我可以有一个对特征对象的静态借用引用吗?
EN

Stack Overflow用户
提问于 2013-10-30 03:44:12
回答 1查看 2.3K关注 0票数 7

有没有一种方法可以让我获得一个对结构的特征实现的静态借用引用:

代码语言:javascript
复制
trait Trait {}

struct Example;
impl Trait for Example {}

这可以很好地工作:

代码语言:javascript
复制
static instance1: Example = Example;

这也可以很好地工作:

代码语言:javascript
复制
static instance2: &'static Example = &Example;

但这不起作用:

代码语言:javascript
复制
static instance3: &'static Trait = &Example as &'static Trait;

失败的原因如下:

代码语言:javascript
复制
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`

或者,是否有一种方法可以从指向结构的全局借用静态指针获取指向特征的借用静态指针:

代码语言:javascript
复制
static instance2: &'static Example = &Example;

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

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

回答 1

Stack Overflow用户

回答已采纳

发布于 2015-11-22 23:09:19

是的,如果特征还实现了Sync,则可以

代码语言:javascript
复制
trait Trait: Sync {}

struct Example;
impl Trait for Example {}

static INSTANCE3: &dyn Trait = &Example;

或者声明您的特征对象也实现了Sync

代码语言:javascript
复制
trait Trait {}

struct Example;
impl Trait for Example {}

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

实现Sync的类型包括

...因此在线程之间共享引用是安全的。

当编译器确定它是合适的时,就会自动实现这个特征。

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

由于您正在共享一个引用,因此任何线程都可以调用该引用上的方法,因此您需要确保在发生这种情况时没有任何东西会违反Rust的规则。

票数 5
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/19667717

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档