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 {})],
        }
    }
}
mcarton
  • 27,633
  • 5
  • 85
  • 95
Albert
  • 169
  • 2
  • 7

1 Answers1

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.

mcarton
  • 27,633
  • 5
  • 85
  • 95