2 pieces of code which should be equivalent but one throws error

This code works:

    pub fn test1(){
        for i in (0..10){
            for j in (0..10){
                println!("{},{}",i,j)
            }
        }
    }

This code throws a borrow error... but only on j_range not on i_range

    pub fn test2(){
        let i_range = (0..10);
        let j_range = (0..10);
        for i in i_range{
            for j in j_range{
                println!("{},{}",i,j)
            }
        }
    }

I've tried multiple variations including

let mut j_range = (0..10);
..
for j in &j_range{

but none of them seem to work.
I don't understand why I get an error on j_range but not on i_range when their usages are identical.
I also don't understand why it's throwing an error when the exact same code without a variable works.

My end goal is just to give the (0..10) a descriptive name so it reads more clearly (in a more complex program where it's not immediately obvious what the range is)

Range isn't a Copy type, so j_range would get consumed after the first loop through i_range. One solution is to simply clone it each time:

pub fn test2(){
    let i_range = (0..10);
    let j_range = (0..10);
    for i in i_range {
        for j in j_range.clone() {
            println!("{},{}",i,j)
        }
    }
}
2 Likes

That would solve my problem, ty

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.