Rust Compiller maybe bugged

An error occurs at a very simple place. When a reference enters a for loop, there is an implicit conversion to into_iter() on a mutable reference, and as we know, this also implicitly uses the iterator std::slice::IterMut. According to the rules of ownership and borrowing, it is IMPOSSIBLE for the compiler to transfer ownership through a mutable reference, yet this happens. Perhaps there is something I don’t know—can anyone explain?

fn main() {
    let mut vec = vec![1, 2, 3, 4, 5];
    let link = &mut vec;
    for val in link {
        println!("{}", val);
    }
    println!("{:?}", link);
}
error[E0382]: borrow of moved value: `link`
   --> src\main.rs:7:22
    |
3   |     let link = &mut vec;
    |         ---- move occurs because `link` has type `&mut Vec<i32>`, which does not implement the `Copy` trait
4   |     for val in link {
    |                ---- `link` moved due to this implicit call to `.into_iter()`
7   |     println!("{:?}", link);
    |                      ^^^^ value borrowed here after move
    |
note: `into_iter` takes ownership of the receiver `self`, which moves `link`
   --> C:\Users\Aqura\.rustup\toolchains\stable-x86_64-pc-windows-msvc\lib/rustlib/src/rust\library\core\src\iter\traits\collect.rs:311:18
    |
311 |     fn into_iter(self) -> Self::IntoIter;
    |                  ^^^^
    = note: this error originates in the macro `$crate::format_args_nl` which comes from the expansion of the macro `println` (in Nightly builds, run with -Z macro-backtrace for more info)
help: consider creating a fresh reborrow of `link` here
    |
4   |     for val in &mut *link {
    |                ++++++```

Upvotes: 0

Views: 43

Answers (0)

Related Questions