【发布时间】:2017-01-21 13:36:55
【问题描述】:
我正在尝试编写一个简单的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')
}
直觉告诉我我需要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
【问题讨论】:
-
好像和this section of the docs有关。
-
投反对票的人是否愿意提出改进这个问题的方法?