Writing a Option/Result/Iterator extension for applying &mut self -> &mut self builder functions

Sorry for the rather complicated title, I do not know how to phrase it in a way that is less ... messy?

So, I had the following (simple) problem:

let reg = Some(".*");

let builder : Option<RegexBuilder> = reg
    .map(RegexBuilder::new)
    // Apply some RegexBuilder::function(&mut self, param) -> &mut Self functions

The last part got me thinking. Well, I could simply use .map(|s| RegexBuilder::new(s).some().function()) and go from there, but that's not so nice syntax-wise. How would it be if writing the following would be possible:

let reg = Some(".*");
    
let builder : Option<RegexBuilder> = reg
    .map(RegexBuilder::new)
    .apply(RegexBuilder::multi_line, false)
    .apply(RegexBuilder::ignore_whitespace, true)
// and so on

That would be awesome and really readable.So I started playing around:

But unfortunaltey I cannot figure out the lifetimes. Also, that POC is not yet made generic over all things. I guess it might be possible to implement these for Option<T>, Result<T, E> and Iterator<Item = T>. Multiple arguments are no possible this way, I guess... maybe different functions for this case (apply1, apply2 and so on).

What do you think and if yes, can you help me figure the lifetimes and generics out? Maybe that's worth a new crate, right?

Related: Variadic generics - pre-RFC - #44 by memoryleak47 - language design - Rust Internals

1 Like

Not super flexible but here is one quick possibility that gets you some of the way, at least.

1 Like