【问题标题】:Effectively take ownership of a borrowed reference to return from a function [duplicate]有效地获得借用引用的所有权以从函数返回[重复]
【发布时间】: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

【问题讨论】:

标签: return rust lifetime


【解决方案1】:

如果&str 是传入参数的一部分,则只能返回它,因为这将允许它具有等于参数的生命周期。本地分配的String 的一部分仅在函数执行期间有效,因此您无法返回它。你将不得不归还(搬出)一个拥有的String

【讨论】:

  • 我会接受这是事实,但我仍然不明白:这与传递拥有的str 在功能上有何不同?我的input: String 的生命周期不是作用于函数体吗?
  • 您不能拥有strBox<str> 除外)。 strString 或常量的一部分。它只能作为参考&str 存在。另一方面,将String 作为参数移动 到函数中,这意味着函数拥有它。拥有的东西也可以再次搬出。
猜你喜欢
  • 2021-12-21
  • 2013-05-18
  • 2019-02-16
  • 1970-01-01
  • 2013-06-14
  • 2022-07-16
  • 2013-12-24
  • 2019-12-03
  • 2021-07-02
相关资源
最近更新 更多