gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 11:33:36 25 4
gpt4 key购买 nike

我了解 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com