string - "Borrowed value does not live long enough", 在循环中使用时丢弃

标签 string loops rust lifetime borrow-checker

我了解 Stringloop 的范围结束时被删除,并且向量 input 包含 trimmed_text 切片.

我想解决方案是将这些切片的所有权转移到 input 或类似的东西。如何做到这一点?

use std::io;

fn main() {
    let mut input: Vec<&str>;

    loop {
        let mut input_text = String::new();
        println!("Type instruction in the format Add <name> to <department>:");
        io::stdin()
            .read_line(&mut input_text)
            .expect("failed to read from stdin");
        let trimmed_text: String = input_text.trim().to_string();

        input = trimmed_text.split(" ").collect();

        if input[0] == "Add" && input[2] == "to" {
            break;
        } else {
            println!("Invalid format.");
        }
    }

    println!("{:?}", input);
}

编译错误:

error[E0597]: `trimmed_text` does not live long enough
  --> src/main.rs:14:17
   |
14 |         input = trimmed_text.split(" ").collect();
   |                 ^^^^^^^^^^^^ borrowed value does not live long enough
...
21 |     }
   |     - `trimmed_text` dropped here while still borrowed
22 | 
23 |     println!("{:?}", input);
   |                      ----- borrow later used here

最佳答案

.split() 返回对 String 的引用,该引用在循环结束时被删除,但您希望 input 能够超过循环的结尾,所以你应该重构它来保存拥有的值而不是引用。示例:

use std::io;

fn example() {
    let mut input: Vec<String>; // changed from &str to String

    loop {
        let mut input_text = String::new();
        println!("Type instruction in the format Add <name> to <department>:");
        io::stdin()
            .read_line(&mut input_text)
            .expect("failed to read from stdin");

        // map str refs into owned Strings
        input = input_text.trim().split(" ").map(String::from).collect();

        if input[0] == "Add" && input[2] == "to" {
            break;
        } else {
            println!("Invalid format.");
        }
    }

    println!("{:?}", input);
}

playground

关于string - "Borrowed value does not live long enough", 在循环中使用时丢弃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66162034/

相关文章:

rust - Rust 中 F# 中字符串的等价 Cons 模式

javascript - 在 ReactJS 中将前一个状态保存到一个数组中

javascript - 当数组中的两位数很少时,查找最大数会返回错误值

Python 用循环创建数据帧

json - 如何使用 serde_json 将 "NaN"反序列化为 `nan`?

rust - 将Rust&str转换为&'static&str

c - 字符串编辑器(无法正常工作)

比较结构体中字符串的第一个字母

java - 将字符串中每个 int 的总和相加

Python 文件读取问题,可能的 infile 循环?