Skip to content

Lints recommeding to use std::iter::once and std::iter::empty #9186

@sgued

Description

@sgued

What it does

It seems suitable to separate it in two lints, one for iter::once and one for iter::empty. They'd look at patterns such as [foo].into_iter() and [].into_iter() and suggest using once and empty instead.

Lint Name

iter_once and iter_empty

Category

pedantic

Advantage

once and empty take less memory than their the arrays or slice iterators for the corresponding use case.

Drawbacks

Depending on the use case, the fix can cause type issues, for example if the iterator is then passed to a function that expects an std::slice::Iter and not a genreric impl Iterator

Example

let a = [foo].iter();
let b = [bar].iter_mut();
let c = [baz].into_iter();
let d = Some(foo).iter();
let e = Some(bar).iter_mut();
let f = Some(baz).into_iter();

Could be written as:

use std::iter;
let a = iter::once(&foo);
let b = iter::once(&mut bar);
let c = iter::once(bar);
let d = iter::once(&foo);
let e = iter::once(&mut bar);
let f = iter::once(bar);

and

let a = [].iter();
let b = [].iter_mut();
let c = [].into_iter();
let d = None.iter();
let e = None.iter_mut();
let f = None.into_iter();

could be written as:

use std::iter;
let a = iter::empty();
let b = iter::empty();
let c = iter::empty();
let d = iter::empty();
let e = iter::empty();
let f = iter::empty();

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-lintArea: New lints

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions