这个问题在这里已有答案:
对于以下代码:
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
结构的概念错误吗?
World
是指str
切片,必须由其他东西拥有。你的函数work
分配一个新的String
(通过get_lines
),并引用它(通过get_first_line
)。当它返回时,String
超出范围并将被删除,因此你不能保持对它的引用,因为它引用的东西不再存在。
如果你想要一个不依赖于其他东西拥有的World
的String
对象,它需要拥有数据本身:包含String
而不是&'a str
。