如何迭代和提取Rust中的for循环的值 [英] How to iterate and extract values out of a for loop in Rust

查看:761
本文介绍了如何迭代和提取Rust中的for循环的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Rust的新手,希望能够理解借贷这样的概念。我正在尝试使用标准输入创建一个简单的二维数组。代码:

 使用std :: io; 

fn main(){
let mut values = [[0; 6]; 6]; // 6 * 6数组

//迭代6次用户输入
for i in 0..6 {
let mut outputs = String :: new();
io :: stdin()。read_line(& mut outputs).expect(
未能读取行,
);

//读取空格分隔列表6个数字。例如:5 7 8 4 3 9
let values_itr = outputs.trim()。split('');
let mut j = 0; $ _ b $ for(_,value)in values_itr.enumerate(){
values [i] [j] = value;
j + = 1;





这不会编译,因为输出变量的生命周期不够长:
$ b

error [E0597]:`outputs`活得不够长
- > src / main.rs:20:5
|
14 |让values_itr = outputs.trim()。split('');
| -------借贷发生在这里
...
20 | }
| ^`输出`在这里下降,同时还借了
21 | }
| - 借来的价值需要活到这里

我怎样才能将迭代值从块中取出数组中的数组(code $ c
$ div class =h2_lin>解决方案 split()
给你substrings(字符串切片)从原始字符串中借用,原始字符串是从第6行 outputs >


  1. 字符串切片不能超过 outputs的范围:当一个循环迭代结束时, outputs 被解除分配。
    由于更长,因此不能将切片存储在那里。
  2. 我们不能借用切片输出通过修改输出。因此即使在 values 之前定义了 String ,我们不能轻易地把字符串从 .split()放入 values ;修改字符串(读入)会导致切片无效。

解决方案需要


  • 使用一个嵌套的数组 String ,并且当您从split迭代器中分配一个元素时,将一个 String ,使用 .to_string()& str 。我会推荐这个解决方案。 (但是 String 的数组并不是那么容易处理,也许已经需要使用 Vec 来代替)。

  • 在构造& str 的嵌套数组之前读取所有输入, code>字符串。这是很好的,如果嵌套数组是你只是暂时需要的。



1 vec![vec![String :: new(); 6]; 6] 改为


I'm new to Rust and looking to understand concepts like borrowing. I'm trying to create a simple two dimensional array using standard input. The code:

use std::io;

fn main() {
    let mut values = [["0"; 6]; 6]; // 6 * 6 array

    // iterate 6 times for user input
    for i in 0..6 {
        let mut outputs = String::new();
        io::stdin().read_line(&mut outputs).expect(
            "failed to read line",
        );

        // read space separated list 6 numbers. Eg: 5 7 8 4 3 9
        let values_itr = outputs.trim().split(' ');
        let mut j = 0;
        for (_, value) in values_itr.enumerate() {
            values[i][j] = value;
            j += 1;
        }
    }
}

This won't compile because the outputs variable lifetime is not long enough:

error[E0597]: `outputs` does not live long enough
  --> src/main.rs:20:5
   |
14 |         let values_itr = outputs.trim().split(' ');
   |                          ------- borrow occurs here
...
20 |     }
   |     ^ `outputs` dropped here while still borrowed
21 | }
   | - borrowed value needs to live until here

How can I get the iterated values out of the block into values array?

解决方案

split() gives you substrings (string slices) borrowed from the original string, and the original string is outputs from line 6.

  1. The string slices can't outlive the scope of outputs: when a loop iteration ends, outputs is deallocated. Since values is longer lived, the slices can't be stored there.
  2. We can't borrow slices of outputs across a modification of outputs. So even if the String outputs itself was defined before values, we couldn't easily put the string slices from .split() into values; modifying the string (reading into it) invalidates the slices.

A solution needs to either

  • Use a nested array of String, and when you assign an element from the split iterator, make a String from the &str using .to_string(). I would recommend this solution. (However an array of String is not at as easy to work with, maybe already this requires using Vec instead.) 1
  • Read all input before constructing a nested array of &str that borrows from the input String. This is good if the nested array is something that you only need temporarily.

1: You can use something like vec![vec![String::new(); 6]; 6] instead

这篇关于如何迭代和提取Rust中的for循环的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆