Composition operator and pipe forward operator in Rust

These operators do not exist in Rust as far as I know. So far I haven't felt much of a need for them, and there is also an effort to keep the core Rust syntax fairly small. For example, Rust used to have explicit message passing operators, but these were removed.

You might be able to use operator overloading to come up with something similar if you want, or just write your own compose or pipe forward functions. I wouldn't be surprised if the Rust team were open to including these in the standard library.


There is no such operator built-in, but it's not particularly hard to define:

use std::ops::Shr;

struct Wrapped<T>(T);

impl<A, B, F> Shr<F> for Wrapped<A>
where
    F: FnOnce(A) -> B,
{
    type Output = Wrapped<B>;

    fn shr(self, f: F) -> Wrapped<B> {
        Wrapped(f(self.0))
    }
}

fn main() {
    let string = Wrapped(1) >> (|x| x + 1) >> (|x| 2 * x) >> (|x: i32| x.to_string());
    println!("{}", string.0);
}
// prints `4`

The Wrapped new-type struct is purely to allow the Shr instance, because otherwise we would have to implement it on a generic (i.e. impl<A, B> Shr<...> for A) and that doesn't work.


Note that idiomatic Rust would call this the method map instead of using an operator. See Option::map for a canonical example.

Tags:

Rust