Skip to content

borrow-checker allows partial reinit of struct that has been moved away, but no use of it. #21232

Closed
@pnkfelix

Description

@pnkfelix

Here is some sample code:

#[derive(Show)]
struct Pair { lft: u8, rgt: u8, }

fn main() {
    let mut p = Pair { lft: 1, rgt: 2 };
    let mut f = move |&mut:| { p.lft = 3; p.rgt };
    p.rgt = 4;
    println!("f: {:?}", f());
    p.lft = 5;
    // println!("p: {:?}", p);
}

This compiles without an error; running it prints f: 2u8.

If you uncomment the last line, you get an error saying "error: use of moved value: p". Likewise if you just attempt to print individual fields.

While I do see the logic being used here ("we are not overwriting the value within the closure itself; we are writing into the uninitialized memory that resulted from moving p into the closure"), it seems potentially confusing.

Is there any reason that we allowing these writes, which cannot be subsequently read? It seems like a situation analogous to moving into a moved-away array (see rust-lang/rfcs#533 )

Metadata

Metadata

Assignees

Labels

A-NLLArea: Non-lexical lifetimes (NLL)A-type-systemArea: Type systemC-feature-requestCategory: A feature request, i.e: not implemented / a PR.NLL-completeWorking towards the "valid code works" goalP-highHigh priority

Type

No type

Projects

No projects

Relationships

None yet

Development

No branches or pull requests

Issue actions