gpt4 book ai didi

rust - 特征对象的静态数组

转载 作者:行者123 更新时间:2023-12-03 11:43:40 29 4
gpt4 key购买 nike

这个问题在这里已经有了答案:





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

(1 个回答)


2年前关闭。




是否可以定义特征对象的静态数组:

#[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
}

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

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.

关于rust - 特征对象的静态数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59679968/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com