Rust - 结构成员的生命周期取决于另一个结构成员

标签 rust lifetime

<分区>

我正在尝试编写一个 Rust 结构。该结构拥有一个指向字符串的引用计数指针,还拥有一个指向同一字符串的字符串切片向量。

此外,我正在尝试编写一个函数来生成此结构。我不确定如何继续。

struct MyStruct<'a> {
    rc_string: Rc<String>,
    vec: Vec<&'a str>
}

fn build_my_struct<'a>(s: &Rc<String>) -> MyStruct<'a> {
    let rc_string = s.clone();
    let mut vec = Vec::new();
    vec.push(&rc_string[0..2]);

    MyStruct {
        rc_string: rc_string,
        vec: vec
    }
}
error[E0515]: cannot return value referencing local variable `rc_string`
  --> src/main.rs:13:5
   |
11 |       vec.push(&rc_string[0..2]);
   |                 --------- `rc_string` is borrowed here
12 | 
13 | /     MyStruct {
14 | |         rc_string: rc_string,
15 | |         vec: vec
16 | |     }
   | |_____^ returns a value referencing data owned by the current function

我了解到vec变量借用了rc_string。编译器不喜欢返回 vec,因为它借用了局部变量 rc_string

但是 rc_string 也被返回了吗?字符串切片在 MyStruct.rc_string 的生命周期内有效?

最佳答案

你还需要借用 Rc 来使用 'a。编译器需要知道来自 String 的切片是否存在于 'a 中。在这种情况下,我们需要为 'a 借用 Rc 并且编译器将知道 Rc 的内部也将存在于 'a.

如果你克隆 s 并将其分配给 rc_string:

  • s 将作为借用的 Rc 保留在函数范围内 'a
  • rc_string 将是 Rc pointer
  • 的所有者

并且编译器将无法知道 rc_string 的切片是否存在于 'a 中。

使用 s 中的切片将起作用:

fn build_my_struct<'a>(s: &'a Rc<String>) -> MyStruct<'a> {
    let mut vec = Vec::new();
    let rc_string = s.clone();

    vec.push(&s[0..2]);

    MyStruct { rc_string, vec }
}

Playground

关于Rust - 结构成员的生命周期取决于另一个结构成员,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56892470/

相关文章:

rust - 为 Rust 编写 C 库绑定(bind)的目的是什么?

rust - Rust 中的 Chain Vector 和 IntoIterator 元素

docker - docker 中的 Rust actix_web 无法实现,为什么?

c++ - 对于非空初始化,lifetime starts before initialization 解决了什么问题?

rust - 创建可变迭代器时出现生命周期错误

notifications - 使用 dbus-rs 的 D-Bus 桌面通知

rust - 无法显示由 peer_addr() 返回的 SocketAddr

rust - 如何减少生活中的矛盾?

rust - 从闭包中返回时的RefMut生命周期错误

rust - 具有可变引用的递归结构中的生存期