Skip to content

let_and_return mistake #1524

Closed
Closed
@leonardo-m

Description

@leonardo-m

This is reduced code:

#![feature(conservative_impl_trait)]

fn pairwise<'a, T>(items: &'a [T]) -> impl Iterator<Item=(&'a T, &'a T)> + 'a {
    items
    .iter()
    .enumerate()
    .flat_map(move |(i, x1)| items[i ..]
                             .iter()
                             .map(move |x2| (x1, x2)))
}

fn foo() -> usize {
    let bars: Vec<Vec<u8>> = vec![];
    let is_valid = |_: &[u8], _: &[u8]| { true };
    let result = pairwise(&bars).filter(|&(c1, c2)| is_valid(c1, c2)).count();
    result
}

fn main() {
    foo();
}

Clippy gives a warning:

warning: returning the result of a let binding from a block. Consider returning the expression directly.
  --> src\main.rs:16:5
   |
16 |     result
   |     ^^^^^^
   |
   = note: #[warn(let_and_return)] on by default
note: this expression can be directly returned
  --> src\main.rs:15:18
   |
15 |     let result = pairwise(&bars).filter(|&(c1, c2)| is_valid(c1, c2)).count();
   |                  ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

But following that advice breaks the code:

error: `bars` does not live long enough
  --> ...\src\main.rs:16:1
   |
15 |     pairwise(&bars).filter(|&(c1, c2)| is_valid(c1, c2)).count()
   |               ---- borrow occurs here
16 | }
   | ^ `bars` dropped here while still borrowed
   |
   = note: values in a scope are dropped in the opposite order they are created

error: aborting due to previous error

Metadata

Metadata

Assignees

No one assigned

    Labels

    C-bugCategory: Clippy is not doing the correct thingE-mediumCall for participation: Medium difficulty level problem and requires some initial experience.T-middleType: Probably requires verifiying types

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions