Reuse range for iteration

I am trying to figure out how to use ranges with iterators. If I declare a range and use it with an iterator, can this range be reused with another iterator? For example, this does not compile:

fn main() {
    let smallr = 0..10;
    for i in smallr {
        println!("value is {}", i);
    }

    //let smallr = 0..15;  re-defining smallr will work!
    let sum  = smallr.fold(0, |sum, x| sum + x);
    println!("{}", sum);
}
+4
source share
1 answer

Range type Rangedoes not implement Copy. Therefore, using a range in a for loop will consume it. If you want to create a copy of the range, you can use .clone():

for i in smallr.clone() {
    println!("value is {}", i);
}

, ( afaik , Range Copy). . , , .

:

fn main() {
    let mut smallr = 0..10;

    println!("first: {:?}", smallr.next());
    for i in smallr.clone() {
        println!("value is {}", i);
    }
}

first: Some(0)
value is 1
value is 2
value is 3
value is 4
value is 5
value is 6
value is 7
value is 8
value is 9

, .

+3

Source: https://habr.com/ru/post/1016563/


All Articles