Skip to content

Pattern reborrows get assigned the wrong lifetime in for loops' LHS. #17068

Closed
@eddyb

Description

@eddyb

These two work:

fn foo<'a>(v: &'a [uint], f: |&'a uint|) {
    for x in v.iter() { f(x); }
}
fn foo<'a>(v: &'a [uint], f: |&'a uint|) {
    for x in v.iter() {
        let  &ref x = x;
        f(x);
    }
}

This doesn't:

fn foo<'a>(v: &'a [uint], f: |&'a uint|) {
    for &ref x in v.iter() { f(x); }
}
error: borrowed value does not live long enough
fn foo<'a>(v: &'a Vec<uint>, f: |&'a uint|) {for &ref x in v.iter() {f(x);}}
                                                           ^~~~~~~~
note: reference must be valid for the lifetime 'a as defined on the block...
fn foo<'a>(v: &'a Vec<uint>, f: |&'a uint|) {for &ref x in v.iter() {f(x);}}
                                            ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
note: ...but borrowed value is only valid for the block
fn foo<'a>(v: &'a Vec<uint>, f: |&'a uint|) {for &ref x in v.iter() {f(x);}}
                                            ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

The patterns may seem redundant, but while the original code had &(_, ref x), that is not necessary to demonstrate the issue.
The error suggests the lifetime used for x is the lifetime of the v.iter() rvalue, instead of 'a from slice::Items<'a, uint>.

cc @pcwalton

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions