Use of moved value


#1

This is my trivial code:

fn main()
{
  let r1 = 0..10;
  for x in r1
  {
    println!("{}", x)
  }
println!("{}", r1.len());
}

compiler doesn’t like.
use of moved value r1.
Ok
What is the best way to fix if i wanr re-use r1?

Thx.


#2

You can clone it, for x in r1.clone().

Or if you make r1 mutable, you can iterate it in-place, for x in r1.by_ref() or for x in &mut r1 – but then you’ll always see len() == 0 if there was no break from the loop.

If you wonder why the range can’t be a Copy type, see:
https://github.com/rust-lang/rust/pull/27186


#3

Thanks Cuviper, very interesting.