2
fn main() {
    let number_list = vec![34, 50, 25, 100, 65];

    let mut largest = number_list[0];

    for number in number_list {
        if number > largest {
            largest = number;
        }
    }

    println!("The largest number is {}", largest);
    assert_eq!(largest, 100);
}

Shouldn't the ownership of first element in the array be given to largest and hence it shouldn't be usable in loop?

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
Yeetesh Pulstya
  • 99
  • 1
  • 10
  • It looks like your question might be answered by the answers of [Do all primitive types implement the Copy trait?](https://stackoverflow.com/q/41413336/155423). If not, please **[edit]** your question to explain the differences. Otherwise, we can mark this question as already answered. – Shepmaster Oct 15 '19 at 13:43

1 Answers1

3

number_list is a list of integers, and integers implement the Copy trait, which means that they are never moved, but are copied instead. For this reason the array keeps ownership of its elements, and largest and number get copies of these elements.

If you try to do the same with a non-copy type, then you get an error:

struct WrappedInt(i32);

fn main() {
    let number_list = vec![34, 50, 25, 100, 65]
        .into_iter()
        .map(|x| WrappedInt(x))
        .collect::<Vec<_>>();

    let mut largest = number_list[0];

    for number in number_list {
        if number.0 > largest.0 {
            largest = number;
        }
    }

    println!("The largest number is {}", largest.0);
    assert_eq!(largest.0, 100);
}

playground

gives:

error[E0507]: cannot move out of index of `std::vec::Vec<WrappedInt>`
 --> src/main.rs:9:23
  |
9 |     let mut largest = number_list[0];
  |                       ^^^^^^^^^^^^^^
  |                       |
  |                       move occurs because value has type `WrappedInt`, which does not implement the `Copy` trait
  |                       help: consider borrowing here: `&number_list[0]`
Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
Jmb
  • 18,893
  • 2
  • 28
  • 55