Suggestion for helper for writing `fmt::Debug` impls with nested structure

I sometimes wonder whether we don’t perhaps want a feature where we can write something like

fn demo() -> impl Debug {
    Debug {
        fmt: |f| f.write_str("wow!"),
    }
}

(click here to read the rest; I don’t want to distract from this thread too much with long off-topics deliberations)

In this world, you could also write

let mut n = 0;
let iterator1 = move Iterator<Item = i32> {
    next: || {
        n += 1;
        Some(n)
    },
};

return iterator1;

or

let mut n = 0;
let iterator2 = Iterator<Item = i32> {
    next: || {
        n += 1;
        Some(n)
    },
    size_hint: || (usize::MAX, None),
};

for n in iterator2 {
    if random() {
        break;
    }
}

or

fn range(mut low: i32, high: i32) -> impl Iterator<Item = i32> {
    assert!(low <= high);
    move Iterator<Item = i32> {
        next: || (low < high).then(|| {
            let item = low;
            low += 1;
            item
        }),
        size_hint: || {
            match (high - low).try_into() {
                Ok(s) => (s, Some(s)),
                Err(_) => (usize::MAX, None),
            }
        }
    }
}

Such ad-hoc anonymous trait implementations would be a lot like closures (but not actually the same, just the syntax I came up with is inspired by closures) – but the killer feature of this would be that multiple methods can have mutable access to captured variables, see e.g. the range function above, (which means this is more capable than simple helper functions taking multiple closures, on for each method). Another great feature would be that this could support convenient variable capture despite implementing generic methods. (As given that generic closures do not exist in Rust.)

How to handle super traits? How to name parameter of a generic method? I don’t know… but a MVP probably doesn’t necessarily need to address all this, anyways.

Sorry if this is taking it somewhat off-topic as it’s more of a language feature proposal, going far beyond (both in scope and time-frame) a simple library addition. (Also I haven’t cross-checked at all against potential existing proposals.)

1 Like