Skip to content

Lambda argument lifetime is tied to lifetime of unrelated iterator #92093

Closed
@starptr

Description

@starptr

It looks like the lifetime of the argument in str_to_i32 is tied to the line iterator for some reason, even though they can have different lifetimes:

use std::io::{BufRead, BufReader, Result};

fn main() -> Result<()> {
    let input = "\n28, 36, 1, 3, 9 \n 69, 420, 21, 22, 23".as_bytes();
    let reader = BufReader::new(input);

    let str_to_i32 = |str| i32::from_str_radix(str, 10).unwrap();

    let mut lines = reader.lines().map(|wrapped| wrapped.unwrap());

    for _i in 0..1 {
        let line = lines.next().unwrap();
        // NOTE: line that errors
        let _nums = line.split_whitespace().map(str_to_i32);
    }
    Ok(())
}

I expect this code to compile. Instead, rustc complains that

error[E0597]: `line` does not live long enough
  --> test.rs:14:21
   |
14 |         let _nums = line.split_whitespace().map(str_to_i32);
   |                     ^^^^^^^^^^^^^^^^^^^^^^^     ---------- borrow later used here
   |                     |
   |                     borrowed value does not live long enough
15 |     }
   |     - `line` dropped here while still borrowed

error: aborting due to previous error

Meta

rustc --version --verbose:

rustc 1.57.0 (f1edd0429 2021-11-29)
binary: rustc
commit-hash: f1edd0429582dd29cccacaf50fd134b05593bd9c
commit-date: 2021-11-29
host: x86_64-unknown-linux-gnu
release: 1.57.0
LLVM version: 13.0.0

Same behavior on both beta and nightly.

(Backtrace is irrelevant here.)

Metadata

Metadata

Assignees

No one assigned

    Labels

    C-bugCategory: This is a bug.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions