特征对象的静态数组

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
}

而不是每个 Test 个实例有一个 _arr

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

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

你想要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 {})];
}

来自 Sync 的文档:

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