Chained .map()s - can't return reference to data owned by this function

Sorry there's been a misunderstanding - I don't need a side-channel like you're showing, just the flow of the main data through the "pipe".

However your example is useful - I assumed I could just use let mut counter but the two closures seem to be considered simultaneous, interesting.

I don't think Rust was deliberately designed that way, but that focus on ownership just makes many “sloppy” programming styles (as in: I don't want to care about memory allocations, I don't want to care about types, I don't want to care about liveness, I don't wan't to care about… “unimportant things”) infeasible.

Case to the point:

Indeed, in Rust you can always predict what happens in [almost] any line of code. And while compiler offers ways to reduce the boilerplate it doesn't offer “just do what I mean, not what I wrote… I don't care about details” constructs.

This is significantly different approach from the “mainstream languages” of today which pride themselves on being as magic as possible (as thus allowing as sloppy code as possible).

I know I found Rust's pedantry annoying at first, but it offers rich payback when debugging time comes: all these little corner-cases which are not handled because they are “unimportant” immediately become visible in a Rust program and it's very easy to go from the failure point to the place where bug actually happens using these breadcrumbs.

Of course if that is not important for you are you would rather only care about “happy path”… then maybe Rust is not the best choice for such a task?

Well, they are not quite simultaneous, but they are interleaving. Consider the output from this:

pub fn main() {
    let log = core::cell::RefCell::new(Vec::new());
    let in_arr = [1, 2, 3, 4, 5];
    let out_arr: Vec<_> = in_arr
        .filter(|&x| { log.borrow_mut().push("filter"); x % 2 == 0 })
        .map(|x| { log.borrow_mut().push("map"); x * 2 })
    println!("{in_arr:?} => {out_arr:?}");
    println!("Log: {log:?})");

Output would be: "filter", "filter", "map", "filter", "filter", "map", "filter"

Two closures change one variable in the interleaved fashion thus without internal mutability this wouldn't be allowed.

And in your original example objects are dropped too early! The go-to solution for that in Rust is Rc/Arc, but since, unlike Swift, these are not hidden people tend to pick something more efficient if they have a choice.

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.