Ownership structures


#1

Hello. Why do I use the structure after the transfer of ownership? This code works:

struct Simple {
    int: i32
}

fn take(a: Simple) {
    //code
}

fn main() {
    let mut x = Simple { int: 4 };
    take(x);
    x.int = 5;
}

In Rustbook i saw that if we pass the possession of binding, the type of data which does not implement Copy, we can not then use the same binding.
We can not use the binding after the transfer of ownership. We can only use it if the type implements Copy and Clone, yes? Why not with the structures? I’m confused…


#2

If you try to use it here, you’ll get an error. But you’re not using it, you’re assigning a new value to it. The old one is invalid, but giving it a new value is fine.


#3

There ought to be a lint for a case like this though.
Because you are allowed to assign a new value but never to use it,
simply trying to print the new x.int will result in an error: use of moved value
http://is.gd/jeXyUr


#4

Ah, but this is an edge case. If you replace the whole thing…
https://play.rust-lang.org/?gist=a756353958a0879ac7e1&version=stable

which seems like it should be identical, but there’s no current way to
track all of the fields and tell which ones were replaced or not.


#5

You’re right, this behaviour is a bit counter-intuitive though.
The way I understood ownership and moving so far was that, everything named x ought to be forbidden to use (meaning, “do anything with”) after the take(x) in this scope.
Unless you write let x =... of course.


#6

Partial reinitialization is a bug: https://github.com/rust-lang/rust/issues/21232