Skip to content

Move+return in a for loop "moving out of captured outer immutable variable in a stack closure" #4654

Closed
@SimonSapin

Description

@SimonSapin

Hi,

I have some code similar to this:

fn test() -> Option<~str> {
    let moved = ~"";
    for (~[1]).each |_| {
        return Some(moved)
    }
    None
}

Compiler output:

move_for.rs:4:20: 4:25 error: moving out of captured outer immutable variable in a stack closure
move_for.rs:4         return Some(moved)
                                  ^~~~~
error: aborting due to previous error

Making the variable mutable does not helpe. I am confident that this move should be fine: the variable is not used afterwards because of the return statement. A very similar code compiles fine when no closure is involved:

fn test() -> Option<~str> {
    let moved = ~"";
    loop {
        return Some(moved)
    }
}

Am I seeing a guarantee that the compiler doesn’t or is the compiler seeing a risk that I don’t?

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-lifetimesArea: Lifetimes / regions

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions