2

Is it possible to define static array of trait objects:

#[macro_use]
extern crate lazy_static;

trait Tr {}

struct A {}
impl Tr for A {}

struct B {}
impl Tr for B {}

lazy_static! {
    static ref ARR: [Box<dyn Tr>;2] = [Box::new(A {}), Box::new(B {})];
    // error[E0277]: `(dyn Tr + 'static)` cannot be shared between threads safely
}

Instead of having one _arr per each Test instance:

struct Test {
    arr: [Box<dyn Tr>; 2],
}

impl Default for Test {
    fn default() -> Test {
        Test {
            arr: [Box::new(A {}), Box::new(B {})],
        }
    }
}
0

1 Answer 1

4

You want Box<dyn Tr + Sync>:

#[macro_use]
extern crate lazy_static;

trait Tr {}

struct A {}
impl Tr for A {}

struct B {}
impl Tr for B {}

lazy_static! {
    static ref ARR: [Box<dyn Tr + Sync>; 2] = [Box::new(A {}), Box::new(B {})];
}

From the documentation of Sync:

Types for which it is safe to share references between threads.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.