thejevans
link
fedilink
11Y

I definitely use that syntax whenever I can. One of the situations where I get stuck with the nested syntax that I shared is when the result of the function call in the for loop affects the inputs for that function call for the next item in the loop. Another is when I am using a heuristic to sort the iterator that I’m looping over such that most of the time I can break from the loop early, which is helpful if the function in the loop is heavy.

@DWin@sh.itjust.works
link
fedilink
2
edit-2
1Y

It feels like maybe this could be a code structure issue, but within your example what about something like this?

fn main(){
    let mut counter = 0;
    let output_array = array.into_iter()
        .map(|single_item| {
            // breaks the map if the array when trying to access an item past 5
            if single_item > 5 {
                break;
            }
        })
        .collect()
        .map(|single_item| {
            // increment a variable outside of this scope that's mutable that can be changed by the previous run
            counter += 1;
            single_item.function(counter);
        })
        .collect();
}

Does that kinda syntax work for your workflow? Maybe it’ll require you to either pollute a single map (or similar) with a bunch of checks that you can use to trigger a break though.

Most of the time I’ve been able to find ways to re-write them in this syntax, but I also think that rusts borrowing system although fantastic for confidence in your code makes refactoring an absolute nightmare so often it’s too much of a hassle to rewrite my code with a better syntax.

thejevans
link
fedilink
11Y

Thanks for this! I’ll see if I can work something like this in.

Create a post

Post funny things about programming here! (Or just rant about your favourite programming language.)

Rules:

  • Posts must be relevant to programming, programmers, or computer science.
  • No NSFW content.
  • Jokes must be in good taste. No hate speech, bigotry, etc.
  • 1 user online
  • 143 users / day
  • 222 users / week
  • 505 users / month
  • 2.9K users / 6 months
  • 1 subscriber
  • 1.54K Posts
  • 34.1K Comments
  • Modlog