将循环中构造的值推入循环外的向量

问题描述 投票:0回答:1

我刚刚被 Rust 弄湿了,我遇到了一个我理解的问题,但无法解决。

在循环内我构造了一些数据。我想将这些数据推送到循环外部定义的向量上。然而,数据的底层数据结构在循环结束时超出了范围。

在给定的示例中,如何将引用的项“复制”到循环外的向量?或者你能解释一下为什么我想做的事情会被人皱眉吗?

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]
所引用的内容?

感谢您的宝贵时间。

loops rust vector scope
1个回答
0
投票

在给定的示例中,我如何将引用的项“复制”到循环外的向量?

lines_left
的类型从
Vec<&str>
更改为
Vec<String>
,并附加
lines_left.push(words[0].to_string())

游乐场

© www.soinside.com 2019 - 2024. All rights reserved.