Subtopic: Loop syntax


#1

Continuing the discussion from Difficulty of learning rust and further work on the learning curve:


Rust beginner notes & questions
#2

As a counter-point, I’ve found I really like the loop{} syntax. Even in languages without do while, I find I’m often writing code that fits the pattern of

loop {
    let x = something_complicated();
    if predicate(x) { break }
    followup_somehow(x);
}

And not needing while (true) or for (;;) (Stroustrup-style) is nice.

On a “this is probably bad style but” note, I’m also rather enamoured by

fn find<T>(mut it: impl Iterator<Item=T>, mut f: impl FnMut(&T) -> bool) -> Option<T> {
    loop {
        let x = it.next()?;
        if f(&x) { return Some(x) }
    }
}

https://play.rust-lang.org/?gist=f87020e0249877bae4e8cb374027cb0b

(Even if I probably wouldn’t actually write code like that “for real”.)


#3

I like the recommended Ada style here: use structured loops (for, while…) if they do the job, but as soon as you need to mess with their control flow via breaks, continues or early returns, consider using a raw loop instead in order to warn the reader about the unusual control flow.


#4

Yes, I like this!


#5

Or better yet, use iterator combinators for great composability. :slight_smile:


#6

I consider these as another kind of structured loop :stuck_out_tongue:


#7

Ah I see, fair enough :yum:

I see them in the more declarative haskellian light of “data flow”.