此问题在此处已有答案:
"Borrowed value does not live long enough", dropped when used in a loop(2个答案)
上个月关门了。
我只是让我的脚趾湿与 rust ,我遇到了一个问题,我明白,但无法修复。
在一个循环中,我构造了一些数据。我想把这些数据推到一个在循环外部定义的向量上。然而,这些数据有一个底层数据结构,在循环结束时会超出范围。
在给定的例子中,我如何将引用项“复制”到循环外的vector中?或者你能解释为什么我试图做的事情是不受欢迎的。
use std::io::{self, BufRead};
/*
* Let's read some lines from stdin and split them on the delimiter "|".
* Store the string on the left side of the delimiter in the vector
* "lines_left".
*/
fn main() {
let stdin = io::stdin();
// in "scope: depth 1" we have a mutable vector called "lines_left" which
// can contain references to strings.
let mut lines_left: Vec<&str> = Vec::new();
// For each line received on stdin, execute the following in
// "scope: depth 2".
for stdin_result in stdin.lock().lines() {
// _Jedi handwave_ "there is no error". Store the "str" in the inmutable
// variable "string". (Type = "&str" ).
let string = stdin_result.unwrap();
// Split the string on the "|" character. This results in a vector
// containing references to strings. We call this vector "words".
let words: Vec<&str> = string.split("|").collect();
// Push the string reference at index 0 in the vector "lines_left".
// FIXME: This is not allowed because:
// The string reference in the vector "words" at index 0,
// points to the underlying data structure "string" which is defined
// in "scope: depth 2" and the data structure "lines_left" is defined
// in "scope: depth 1". "scope: depth 2" will go out-of-scope below
// this line. I need a "copy" somehow...
lines_left.push(words[0])
}
}
字符串
编译此代码将导致:
error[E0597]: `string` does not live long enough
--> main.rs:25:32
|
21 | let string = stdin_result.unwrap();
| ------ binding `string` declared here
...
25 | let words: Vec<&str> = string.split("|").collect();
| ^^^^^^^^^^^^^^^^^ borrowed value does not live long enough
...
34 | lines_left.push(words[0])
| ------------------------- borrow later used here
35 | }
| - `string` dropped here while still borrowed
error: aborting due to previous error
For more information about this error, try `rustc --explain E0597`.
型
所以我想我可以复制一个words[0]
引用的东西?
感谢您抽出宝贵的时间。
1条答案
按热度按时间kupeojn61#
你的思路是正确的,你确实需要一个副本。但是
lines_left
的类型是错误的,它不能容纳引用,因为引用必须引用更长时间的东西。因此:在给定的例子中,我如何将引用的项“复制”到循环外的向量?
将
lines_left
的类型从Vec<&str>
更改为Vec<String>
,并添加lines_left.push(words[0].to_string())
。to_string()
可以方便地将&str
复制到新创建的String
中。Playground