Skip to content

Closures should infer to capture by copy #36569

@bluss

Description

@bluss

Inspired by a common stumbling block with Iterator::flat_map.

This code does not compile:

(0..10).flat_map(|i| (0..i).map(|j| i + j))
error: `i` does not live long enough

(playground code)

The problem: i is a local variable and captured by reference in a closure we're trying to return. It's an integer, its data size is equal or smaller as a value instead of a reference.

Can rustc infer that the closure should capture i by "move" here (Copy)?

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-closuresArea: Closures (`|…| { … }`)A-inferenceArea: Type inferenceC-enhancementCategory: An issue proposing an enhancement or a PR with one.C-feature-requestCategory: A feature request, i.e: not implemented / a PR.T-langRelevant to the language team

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions