有效地获取借用引用的所有权以从函数返回

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)

the*_*472 5

&str如果 a 是传入参数的一部分,则只能返回 a ,因为这将允许它具有与参数相同的生命周期。本地分配的切片String仅在函数的持续时间内有效,因此您无法返回它。您必须归还(搬出)拥有的String

  • 您不能拥有“str”(除了“Box<str>”)。`str` 是 `String` 或常量的切片。它只能作为引用“&str”存在。另一方面,传递“String”作为参数会将其*移动*到函数中,这意味着该函数拥有它。而且所拥有的东西也可以再次移出。 (2认同)