Studying Rust and Kotlin at the moment, I wonder whether something as neat as Kotlin’s Scope functions (let
, apply
, run
, etc.) could be / are implemented in Rust?
On a similar note, I’ve just created a trait + blanket implementation containing functions that apply a closure to a value given the value of a second parameter is true
. I’m sure someone must have done that better than me, already. Anybody know who / where? I found this hard to google:
// trait definition with default implementation
trait ApplyIf
where
Self: Sized + Clone,
{
fn apply_if(self, modifier: impl Fn(Self) -> Self, condition: bool) -> Self {
if condition {
modifier(self)
} else {
self
}
}
fn cloned_apply_if(self: &Self, modifier: impl Fn(&Self) -> Self, condition: bool) -> Self {
if condition {
modifier(self)
} else {
self.clone()
}
}
}
// blanket implementation
impl<T: Sized + Clone> ApplyIf for T {}
// usage
fn double_odds(val: usize) -> usize {
val.apply_if(|v| v * 2, val % 2 == 1)
}
What’s nice about it is that you can chain the apply_if
calls. I used it for formatting / colorizing terminal output.