Can I have a static borrowed reference to a trait object?

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

trait Trait: Sync {}

struct Example;
impl Trait for Example {}

static INSTANCE3: &dyn Trait = &Example;

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;

Types that implement Sync are those

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

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

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.

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.

Leave a Comment