Skip to content

Confusing lifetime inference with a closure #36867

Closed
@hardenedapple

Description

@hardenedapple

The code below compiles and runs as I expect, but when the type annotation is uncommented rustc gives lifetime errors.

I've seen a few similar but not quite the same issues, but I don't think this particular one is already logged (apologies if that's not the case).

use std::vec::Vec;
fn main() {
    let nodes = (0..3).collect::<Vec<u32>>();
    let references = nodes.iter().map(
        |x
        // : &u32 // If this line is uncommented I get lifetime problems
        | x).collect::<Vec<_>>();
    println!("references: {:?}", references);
}

Using the trivial function below instead of a closure compiles without errors.

fn return_reference(x: &u32) -> &u32 {
    x
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-closuresArea: Closures (`|…| { … }`)A-inferenceArea: Type inferenceA-lifetimesArea: Lifetimes / regionsC-enhancementCategory: An issue proposing an enhancement or a PR with one.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions