Skip to content

let_and_return false positive #1669

@leonardo-m

Description

@leonardo-m
#![feature(conservative_impl_trait)]
fn pairs<'a, T>(items: &'a [T]) -> impl Iterator<Item=(&'a T, &'a T)> + 'a {
    items.iter().map(|i| (i, i))
}
fn foo() -> usize {
    let data = vec![0, 1, 2, 3];
    let result = pairs(&data).count();
    result
}
fn main() {
    foo();
}
warning: returning the result of a let binding from a block. Consider returning the expression directly.
 --> src\main.rs:8:5
  |
8 |     result
  |     ^^^^^^
  |
  = note: #[warn(let_and_return)] on by default
note: this expression can be directly returned
 --> src\main.rs:7:18
  |
7 |     let result = pairs(&data).count();
  |                  ^^^^^^^^^^^^^^^^^^^^
  = help: for further information visit https://github.com/Manishearth/rust-clippy/wiki#let_and_return

If I modify the code as suggested, it stops compiling:

#![feature(conservative_impl_trait)]
fn pairs<'a, T>(items: &'a [T]) -> impl Iterator<Item=(&'a T, &'a T)> + 'a {
    items.iter().map(|i| (i, i))
}
fn foo() -> usize {
    let data = vec![0, 1, 2, 3];
    pairs(&data).count()
}
fn main() {
    foo();
}

Rustc gives:

error: `data` does not live long enough
 --> ...\main.rs:8:1
  |
7 |     pairs(&data).count()
  |            ---- borrow occurs here
8 | }
  | ^ `data` dropped here while still borrowed
  |
  = note: values in a scope are dropped in the opposite order they are created

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