gpt4 book ai didi

rust - 从对象池中借用时解决省略的静态生命周期

转载 作者:行者123 更新时间:2023-11-29 08:25:12 28 4
gpt4 key购买 nike

这是我目前面临的问题的简化版本。

trait SuperObject {
fn object_name(&self) -> String;
}

trait Inspect {
fn inspect(&self);
}

impl Inspect for SuperObject {
fn inspect(&self) {
println!("I am a Superobject.");
}
}

struct Object {
name: String
}

impl SuperObject for Box<Object> {
fn object_name(&self) -> String {
format!("I am {}.", self.name.clone())
}
}

struct ObjectPool {
object1: Box<Object>,
object2: Box<Object>,
object3: Box<Object>
}

impl ObjectPool {
pub fn new() -> ObjectPool {
ObjectPool {
object1: Box::new(Object { name: String::from("Object 1") }),
object2: Box::new(Object { name: String::from("Object 2") }),
object3: Box::new(Object { name: String::from("Object 3") })
}
}
fn all_objects(&self) -> Vec<&SuperObject> {
let mut ret: Vec<&SuperObject> = Vec::new();
ret.push(&self.object1);
ret.push(&self.object2);
ret.push(&self.object3);
ret
}
}

fn main() {
let objectpool: ObjectPool = ObjectPool::new();
let allobjects: Vec<&SuperObject> = objectpool.all_objects();
for i in &allobjects {
println!("{}", i.object_name());
// Comment the following line in order to drop error E0597
i.inspect(); // FIXME: borrowed value must be valid for the static lifetime
}
}

尝试编译这段代码时的错误如下:

error[E0597]: `objectpool` does not live long enough
--> src/main.rs:50:41
|
50 | let allobjects: Vec<&SuperObject> = objectpool.all_objects();
| ^^^^^^^^^^ does not live long enough
...
56 | }
| - borrowed value only lives until here
|
= note: borrowed value must be valid for the static lifetime...

error: aborting due to previous error

经过多次搜索,据我了解,被实例化的对象具有默认的静态生命周期,如 https://doc.rust-lang.org/book/second-edition/ch19-02-advanced-lifetimes.html 中所述

我相信 ObjectPool 的 all_objects 方法的输出被编译器忽略为静态的,正如我尝试调试代码片段时引发的错误之一所证明的那样:

error[E0308]: mismatched types
--> src/main.rs:42:18
|
42 | ret.push(&self.object2);
| ^^^^^^^^^^^^^ expected struct `std::boxed::Box`, found reference
|
= note: expected type `std::boxed::Box<SuperObject>`
found type `&std::boxed::Box<SuperObject + 'static>`

不涉及完全废弃对象池的最佳行动方案是什么?或者是否有适合 Rust 实现的更优雅的抽象?

最佳答案

问题是您的 impl Inspect for SuperObject。为另一个特征实现一个特征不会达到您期望的效果。基本上规则是:永远不要这样做。从本质上讲,这意味着只有当您拥有 &(SuperObject + 'static) 时,您才能将其视为 Inspect。你想要的是

impl<T: SuperObject + ?Sized> Inspect for T {
fn inspect(&self) {
println!("I am a Superobject.");
}
}

关于rust - 从对象池中借用时解决省略的静态生命周期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46883242/

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