所以我有这个特征和一个实现它的结构:
trait Trait {
fn foo(&self) -> u64;
}
/// No Copy trait supported because it's expensive
struct Expensive {
id: u64,
}
impl Trait for Expensive {
fn foo(&self) -> u64 {
self.id
}
}我有另一个结构,我希望它是全局的,它包含这样的特征:
struct Cheap {
pub item: Box<dyn Trait>,
}
thread_local! {
static CHEAP: Cheap = Cheap {
item: Box::new(Expensive {
id: 4
})
}
}
fn trait_item() -> Box<dyn Trait> {
CHEAP.with(|c| c.item)
}这会失败,因为
error[E0507]: cannot move out of `c.item` which is behind a shared reference
--> src/main.rs:35:20
|
35 | CHEAP.with(|c| c.item)
| ^^^^^^ move occurs because `c.item` has type `std::boxed::Box<dyn Trait>`, which does not implement the `Copy` trait总是在.with(...)部件中进行处理并不是真正可行的,因为接受Trait的一些函数并不关心它来自哪里。所以我尝试返回一个对它的引用:
fn trait_item<'a>() -> &'a Box<dyn Trait> {
CHEAP.with(|c| &c.item)
}这也会失败,因为我不能将引用发送到with之外
error[E0495]: cannot infer an appropriate lifetime for borrow expression due to conflicting requirements
--> src/main.rs:33:20
|
33 | CHEAP.with(|c| &c.item)
| ^^^^^^^
|
note: first, the lifetime cannot outlive the anonymous lifetime #2 defined on the body at 33:16...
--> src/main.rs:33:16
|
33 | CHEAP.with(|c| &c.item)
| ^^^^^^^^^^^
note: ...so that reference does not outlive borrowed content
--> src/main.rs:33:20
|
33 | CHEAP.with(|c| &c.item)
| ^^^^^^^
note: but, the lifetime must be valid for the lifetime `'a` as defined on the function body at 32:15...
--> src/main.rs:32:15
|
32 | fn trait_item<'a>() -> &'a Box<dyn Trait> {
| ^^
note: ...so that reference does not outlive borrowed content
--> src/main.rs:33:5
|
33 | CHEAP.with(|c| &c.item)
| ^^^^^^^^^^^^^^^^^^^^^^^因此,我将整个内容封装在一个Rc中,如下所示:
struct Cheap {
pub item: Rc<Box<dyn Trait>>,
}
thread_local! {
static CHEAP: Cheap = Cheap {
item: Rc::new(Box::new(Expensive {
id: 4
}))
}
}
fn trait_item() -> Rc<Box<dyn Trait>> {
CHEAP.with(|c| c.item.clone())
}但现在,克利皮抱怨道:
warning: usage of `Rc<Box<T>>`
--> src/main.rs:41:15
|
41 | pub item: Rc<Box<dyn Trait>>,
| ^^^^^^^^^^^^^^^^^^ help: try: `Box<dyn Trait>`
|
= note: `#[warn(clippy::redundant_allocation)]` on by default
= help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#redundant_allocation
warning: usage of `Rc<Box<T>>`
--> src/main.rs:53:20
|
53 | fn trait_item() -> Rc<Box<dyn Trait>> {
| ^^^^^^^^^^^^^^^^^^ help: try: `Box<dyn Trait>`
|
= help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#redundant_allocation
warning: 2 warnings emitted我是不是遗漏了什么,或者实际上不可能做到clippy在这里推荐的?
发布于 2020-10-12 17:37:35
也可以将特征对象包装在Rc中,因为Rc也是一个指针。
因此,如果有Rc<Box<T>>,就有两个分配:一个用于T,另一个用于Box (另一个指针,现在位于堆上)。取而代之的是,使用Rc<dyn MyTrait>来只有一个分配。
https://stackoverflow.com/questions/64311229
复制相似问题