2

When I read the Rust documentation on generics, I found a weird question about ownership. Looking at the following snippet:

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);
}

Why doesn't largest take ownership of the first element of vector? I found that in the previous chapter about vectors, using the borrow syntax let largest = &v[0] would take ownership of the element. Why does this code pass the compiler?

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
钟泽耿
  • 23
  • 3

1 Answers1

5

Lots of primitive types implement the Copy trait - this means that they are copied around when you bind them to other variables. There is no ownership issue when values are copied around.

This is just for demonstration purposes and isn't very practical ... but if you change your example to use a simple dumb struct, you'll see it not longer works (as it doesn't implement Copy):

#[derive(Debug, PartialEq)]
struct S;

fn main() {
    let number_list = vec![S, S, S, S];

    let mut largest = number_list[0];

    for number in number_list {
        if number == largest {
            largest = number;
        }
    }
    println!("The largest number is {:?}", largest);
}

However if you have it implement Copy (and Clone), it'll run fine:

#[derive(Clone, Copy, Debug, PartialEq)]
struct S;

You can play with it in the Playground here if you want

Simon Whitehead
  • 63,300
  • 9
  • 114
  • 138