Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Changing a moved struct #26665

Closed
jbornschein opened this issue Jun 29, 2015 · 3 comments
Closed

Changing a moved struct #26665

jbornschein opened this issue Jun 29, 2015 · 3 comments

Comments

@jbornschein
Copy link

I was very surprised that this code compiles and outputs 1. When I try to print a.val after the assignment I get a compile error -- as I expected.

Assuming A has move semantics, this should IMHO never compile ... and/or, (according to my newbie mental model of move semantics) output a 2.

struct A {
    val: i32
}

fn main() {
    let mut a = A{val: 1};
    let a_ = a;

    a.val = 2;
    println!("a_: {}", a_.val);
}
@steveklabnik
Copy link
Member

/cc @rust-lang/lang

This isn't unsafe or anything, but we may want to change that? Or have a diagnostic of some kind?

@huonw
Copy link
Member

huonw commented Jun 29, 2015

Local variables are semantically memory locations on the stack, which can own values. Move semantics means that something like let a_ = a; moves the value out of a (into a new independent stack slot a_), leaving the latter as an "empty" stack slot. It's possible to reinitialise the slot (i.e. put a new value into it) and continue to use it, e.g. a = A { val: 2 }; println!("{}", a.val); works perfectly OK. Rust somewhat tracks the initialisation state of structs on a per-field basis but it doesn't do this fully, as demonstrated by a.val not working, but it could in future. In other words, Rust allows writing to the individual fields of an empty stack slot, but doesn't then follow this through to allow reading the ones that have been initialised.

It would be unsafe if a.val = 2 caused a_.val to also be 2, as it would be a source of mutable sharing which is the core thing Rust tries to control/protect against.

Closing as not-a-bug, but thanks for filing!

@huonw huonw closed this as completed Jun 29, 2015
@jbornschein
Copy link
Author

Thanks for the explanation!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants