简体   繁体   English

如何在Rust的for循环中使用多个变量?

[英]How to use multiple variables in Rust's for loop?

In the C family of languages, I can do this on one line: 在C语言系列中,我可以在一行中执行此操作:

for(int i = lo, int j = mid+1; i <= mid && j <= hi; i++, j++){
    ...
}

But in Rust... I can only write it like this: 但在Rust ...我只能这样写:

for i in lo..mid+1 {
    let mut j = mid+1;
    if j <= hi {
        break;
    }
    ...
    j += 1;
}

Is there's a more efficient way to implement this? 是否有更有效的方法来实现这一点?


Using an iterator works for above, but using an iterator makes some occasions like using arithmetic troublesome, such as 使用迭代器适用于上面,但使用迭代器会使某些场合像使用算术麻烦,例如

for (int i = 0; i < n; i ++) {
    if (a[i] == ...) {
        i += 5;
    }
}

In Rust, this does not work. 在Rust中,这不起作用。 The variable i will not be incremented by 5, but by 1 instead: 变量i不会增加5,而是增加1:

for i in 0..n {
    if a[i] == ... {
        i += 5;
    }
} 

You can create two parallel range iterators, zip them, then iterate though the combination: 您可以创建两个并行范围的迭代器, zip它们,然后迭代组合:

fn main() {
    let values = [10, 20, 30, 40, 50, 60, 70, 80, 90];
    let lo = 2;
    let mid = 5;
    let hi = 7;

    let early_indexes = lo..(mid + 1);
    let late_indexes = (mid + 1)..(hi + 1);
    for (i, j) in early_indexes.zip(late_indexes) {
        println!("{}, {}", i, j);
        println!("{} - {}", values[i], values[j]);
    }
}

Someday , inclusive ranges will be stabilized , and you should be able to something like this (depending on the eventual syntax): 有一天 ,包容性范围将会稳定 ,你应该能够做到这一点(取决于最终的语法):

let early_indexes = lo...mid;
let late_indexes = (mid + 1)...hi;
for (i, j) in early_indexes.zip(late_indexes) {
    println!("{}, {}", i, j);
    println!("{} - {}", values[i], values[j]);
}

If you are actually iterating though a slice as I've shown for my example, you can also just combine the two iterators directly and ignore the index: 如果您实际上正在迭代迭代,就像我为我的示例所示,您也可以直接组合两个迭代器并忽略索引:

let early_values = values[lo..(mid + 1)].iter();
let late_values = values[(mid + 1)..(hi + 1)].iter();
for (i, j) in early_values.zip(late_values) {
    println!("{}, {}", i, j);
}

The variable i will not be incremented by 5, but by 1 instead. 变量i不会增加5,而是增加1。

Yes, incrementing by a step is annoying, and some day it will also be stabilized . 是的,增加一步是令人讨厌的,有一天它也会稳定下来 In the meantime: 同时:

If you need full control, you can always use while or loop : 如果您需要完全控制,您可以随时使用whileloop

let mut i = 0;
while i < n {
    if a[i] == ... {
        i += 5;
    }

    i += 1;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM