Is there a macro crate you know of that provides similar functionality to kotlin scope functions?

At certain contexts it is really comfortable to use scope functions of kotlin which makes one write a lot less repetitive code.
I was wondering if there are any macro crates to provide a similar syntax ?
here you can see the usage and the details of the scope functions.

Rust natively provides block expressions, so something like:

Person("Alice", 20, "Amsterdam").let {
    println(it)
    it.moveTo("London")
    it.incrementAge()
    println(it)
}

can be written like:

let alice = {
    let mut it = Person::new("Alice", 20, "Amsterdam");
    println!("{}", it);
    it.move_to("London");
    it.increment_age();
    println!("{}", it);
    it
};

I don't know if Kotlin provides this, but at least their example of what the code looks like without the scope function doesn't use it.

But to get nicer syntax you can use tap:

Person::new("Alice", 20, "Amsterdam").tap_mut(|it| {
    println!("{}", it);
    it.move_to("London");
    it.increment_age();
    println!("{}", it);
});
5 Likes

Thank you tap was exactly what I was looking for

The tap crate brings back warm memories of the magrittr package from R, thanks for bringing it to my attention @Kestrer.

1 Like

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.