Sea*_*red 2 return lifetime rust
我正在尝试编写一个简单的prompt函数,它返回一个输入字符串而不带尾随换行符,但我无法返回我的结果,因为它的input寿命不够长。我知道这String::trim_right_matches是返回对 的一部分的借用引用input: String,但我不知道如何获得该数据的所有权或以某种方式复制它以返回它。
我已经转了几个小时了,但没有运气,尽管我知道这种“与借用检查器的斗争”是 Rust 新手的必经之路,所以我想我并不孤单。
use std::io;
use std::io::Write;
fn main() {
println!("you entered: {}", prompt("enter some text: "));
}
fn prompt(msg: &str) -> &str {
print!("{}", msg);
io::stdout().flush()
.ok()
.expect("could not flush stdout");
let mut input = String::new();
io::stdin()
.read_line(&mut input)
.expect("failed to read from stdin");
input.trim_right_matches(|c| c == '\r' || c == '\n')
}
Run Code Online (Sandbox Code Playgroud)
直觉告诉我我需要fn prompt(prompt: &str) -> str代替-> &str,但我无法以编译器接受的方式实现这一点。
error: `input` does not live long enough
--> src/main.rs:22:5
|
22 | input.trim_right_matches(|c| c == '\r' || c == '\n').clone()
| ^^^^^ does not live long enough
23 | }
| - borrowed value only lives until here
|
note: borrowed value must be valid for the anonymous lifetime #1 defined on the block at 9:32...
--> src/main.rs:9:33
|
9 | fn prompt(msg: &str) -> &str {
| ^
error: aborting due to previous error
Run Code Online (Sandbox Code Playgroud)
&str如果 a 是传入参数的一部分,则只能返回 a ,因为这将允许它具有与参数相同的生命周期。本地分配的切片String仅在函数的持续时间内有效,因此您无法返回它。您必须归还(搬出)拥有的String
| 归档时间: |
|
| 查看次数: |
6199 次 |
| 最近记录: |