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

Writing to values after giving up ownership doesn't error #31538

Closed
sophiajt opened this issue Feb 10, 2016 · 4 comments
Closed

Writing to values after giving up ownership doesn't error #31538

sophiajt opened this issue Feb 10, 2016 · 4 comments

Comments

@sophiajt
Copy link
Contributor

Taking this example:

struct Data {
    x: i32,
    y: Vec<i32>
}

fn use_data(mut data: Data) {
    data.x = 1;
    data.y.push(7);
}

fn main() {
    let mut data = Data { x: 0, y: Vec::new() };

    use_data(data);

    data.x = 2;
    //data.y.push(8);
}

Currently, Rust nightly doesn't error on the 'data.x = 2' line, even though we've given up ownership to data. The error does appear if you uncomment the following line and try to do something a little less trivial than assigning to an i32.

Should we treat them the same and warn of any use, whether reading or writing, of any field of a value that we no longer own?

@arielb1
Copy link
Contributor

arielb1 commented Feb 10, 2016

Why should it error?

@bluss
Copy link
Member

bluss commented Feb 10, 2016

The behavior after data is moved from is pretty haphazard, for example

    data.y = vec![];  // is ok
    drop(data.y); // error: use of moved value: `data.y`

@sophiajt
Copy link
Contributor Author

@arielb1 - it's a totally fair question. For me it's about having a mental model that's simple to explain for how ownership works after you've handed off ownership of your data. Like @bluss shows, the current behavior is a mix of errors and non-errors, depending on what you're doing.

I think a simpler mental model might be something like "after you hand off ownership, any read or write to the data will error." Currently, it's something more like "after you hand off ownership, any read will fail and any write will appear to succeed but will not update the value you've handed off. Instead, it updates an invisible copy you can not read. Also, any update (eg .push(x) or drop) will fail"

@alexcrichton
Copy link
Member

Thanks for the report! I think this is the same as #26665 which is in turn described more thoroughly in #21232, so I'm going to close in favor of that.

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

4 participants