struct str属性必须引用? [重复]

问题描述 投票:1回答:1

对于以下代码:

fn get_lines() -> String {
    String::from("Hello\nWorld")
}

fn get_first_line(s: &String) -> &str {
    s.lines().next().unwrap()
}

struct World<'a> {
    a_str: &'a str,
}

fn work<'a>() -> World<'a> {
    let s1 = get_lines();
    let s2 = get_first_line(&s1);

    World { a_str: s2 }
}

fn main() {
    let w = work();
}

我收到以下错误:

error[E0515]: cannot return value referencing local variable `s1`
  --> src/main.rs:17:5
   |
15 |     let s2 = get_first_line(&s1);
   |                             --- `s1` is borrowed here
16 | 
17 |     World { a_str: s2 }
   |     ^^^^^^^^^^^^^^^^^^^ returns a value referencing data owned by the current function

如何使用s2构建结构实例?这是World结构的概念错误吗?

string struct rust
1个回答
1
投票

World是指str切片,必须由其他东西拥有。你的函数work分配一个新的String(通过get_lines),并引用它(通过get_first_line)。当它返回时,String超出范围并将被删除,因此你不能保持对它的引用,因为它引用的东西不再存在。

如果你想要一个不依赖于其他东西拥有的WorldString对象,它需要拥有数据本身:包含String而不是&'a str

另见'dangling references' in the Rust Book

© www.soinside.com 2019 - 2024. All rights reserved.