Search code examples
rustownership

Vector of enum values creates ownership issues


I have two fragments of code which worked well until a few days ago. They look fairly simple:

1.

let mut mask = 0 as c_ulong;
for bit in bits.iter() {
    mask |= *bit as c_ulong;
}

2.

for bit in vec!(...).iter() {
    if res & *bit as c_ulong != 0 {
        bits.push(*bit);
    }
}

The vector iterated vector in both cases contains an enum like:

#[allow(non_camel_case_types)]
#[deriving(PartialEq,Show)]
pub enum SomeEnum {
    BLAH                 = 0x01,
    ...
}

But unfortunately now that code causes the following error on all *bit expressions.

cannot move out of dereference of `&`-pointer

I don't understand this error. Why is it now not allowed? I have a pointer to an immutable vector with enum variants that are practically just int values.

Also, how can I fix it? I know the first case can be transformed to use .into_iter() - that's ok, I don't need that vector afterwards. But in the second fragment, I actually can't use bit twice after .into_iter(). Even though I only compare it the first time!

Am I missing something trivial here?


Solution

  • Your type used to be Copy, but this trait is now opt-in.

    Add #[deriving(Clone, Copy)] (or add Clone and Copy to the list of traits in an existing #[deriving] attribute) to your type. You need to implement both Clone and Copy, because Copy is a subtrait of Clone (as any type that implements Copy can also trivially implement Clone).

    pub trait Copy: Clone { }