Why and when Never_Loop is required?

#1

By using clippy I have to analyse some project and in that project i received clippy error (never_loop) due to following piece of code. I am confused why they used loop, whereas it always running one time (never loop).

fn me(&self) -> T {
for (i, n) in self.table.iter() {
return T::Meg {
cind: i,
cnr: (*nf).into(),
};
}
unsafe { unreachable_unchecked() }
}

so in above for loop entering into loop and immediately returning some value . Can anyone explain me why and when Never Loop is required ?

#2

Well, this can actually be more concise, what type is self.table?


Because you could do something like this (If it’s a HashMap):

fn me(&self) -> T {
    let (i, n) = self.table.iter().next();
    T::Meg {
        cind: i,
        cnr: (*n).into() //Fixed a typo
    }
}

This:

  • Avoids the unsafe code
  • Uses the idiomatic implict return
  • No longer requires the use of a for loop
  • Fixes a typo
  • Keeps clippy happy
#3

Thanks for your prompt reply. So you means that we don’t need this type of for loop, at all. Actually I was thinking that above mentioned for loop could be replaced with if else statement. But, indeed, I want to know the reason behind why they used such kind of loop ( which never be a loop !).

#4

Actually, I’m wrong, I forgot that Iterator::next() returns an Option<T>, so the code should actually be like this:

fn me(&self) -> T {
    if let Some((i, n)) = self.table.iter().next() {
        T::Meg {
            cind: i,
            cnr: (*n).into() 
        }
    } else {unimplemented!()}
}

They might’ve used the loops for aesthetics because using the .next() method looks more complicated if you’re not aware of how loops/iterators work.

#5

Again thanks for your time. However, at this time, I don’t need for any improvement in code. I just want to know the reason behind above mentioned for loop ! why they used such logic which seems to be never-loop. nothing else.

#6

I’ve updated my answer to cover this.

#7

Sorry i posted very quickly. Can you explain me why do you mean by aesthetics in this context… ?

#8

I mean it as in code style, basically just what you want it to be, because it will probably just get optimized away at release compile time.

1 Like