ergonomic pipe operator in rust
@oppi.li · 18d ago · rust · 46 loc · raw · 0 comments
1trait Wrap<T> {2 fn wrap<F, U>(self, f: F) -> U3 where4 F: Fn(T) -> U,5 Self: Sized;6}78impl<T> Wrap<T> for T {9 fn wrap<F, U>(self, f: F) -> U10 where11 F: Fn(T) -> U,12 {13 f(self)14 }15}1617// chain as much as you like!1819// no more of this:20Ok(foo.iter().filter(..).collect())2122// pure bliss:23foo.iter().filter(..).collect().wrap(Ok)242526// more realistic example:27let responses = futures::future::join_all(28 batches29 .iter()30 .map(|batch| self.choose_files_in_batch(&depgraph, batch.as_slice())),31)32.await;333435// ew! thats awful363738// lets fix that:39let responses = batches40 .iter()41 .map(|batch| self.do_async_thing(batch))42 .wrap(futures::future::join_all)43 .await;4445// much better!46
login to post a comment