rust 调用trait中定义的返回引用类型的函数时编译错误:借来的价值活得不够久

1bqhqjot  于 2023-03-30  发布在  其他
关注(0)|答案(1)|浏览(138)

调用trait中定义的返回引用类型的函数时编译错误:借来的价值活得不够久
下面是我的问题的一个样本复制:

use std::rc::Rc;

trait Bundle<'a> {
    fn id(&'a self) -> &'a str;
}

struct Demo {
    id: String,
}

impl<'a> Bundle<'a> for Demo {
    fn id(&'a self) -> &'a str {
        &self.id
    }
}

fn x(bundle: Rc<dyn Bundle<'_>>, file: &str) -> String {
    let id = bundle.id();
    format!("bundle/{}/{}", id, file)
}

fn main() {
    let demo = Rc::new(Demo {
        id: String::from("demo"),
    });
    println!("{}", x(demo as Rc<dyn Bundle>, "hello.txt"));
}

编译器给出以下错误:

error[E0597]: `bundle` does not live long enough
  --> src/main.rs:18:14
   |
17 | fn x(bundle: Rc<dyn Bundle<'_>>, file: &str) -> String {
   |      ------ has type `Rc<dyn Bundle<'1>>`
18 |     let id = bundle.id();
   |              ^^^^^^^^^^^
   |              |
   |              borrowed value does not live long enough
   |              argument requires that `bundle` is borrowed for `'1`
19 |     format!("bundle/{}/{}", id, file)
20 | }
   | - `bundle` dropped here while still borrowed

我是一个新手,在我的理解中,在第19行的format!()语句之后,我不再借用bundle。那么为什么rustc认为它“仍然是借用的”呢?

eimct9ow

eimct9ow1#

我犯了一个愚蠢的错误。感谢@jmb在评论部分给出的答案,我现在将代码更改为以下代码来修复它:

use std::rc::Rc;

trait Bundle {
    fn id(&self) -> &str;
}

struct Demo {
    id: String,
}

impl Bundle for Demo {
    fn id(&self) -> &str {
        &self.id
    }
}

fn x(bundle: Rc<dyn Bundle>, file: &str) -> String {
    let id = bundle.id();
    format!("bundle/{}/{}", id, file)
}

fn main() {
    let demo = Rc::new(Demo {
        id: String::from("demo"),
    });
    println!("{}", x(demo as Rc<dyn Bundle>, "hello.txt"));
}

顺便说一句,我也尝试继续使用显式生命周期。泛型参数应该在函数上,而不是在trait上。

trait Bundle {
    fn id<'a>(&'a self) -> &'a str;
}

相关问题