Cleaner way of writing functions with method call syntax?

I recently found myself doing something like this to get method call syntax:

pub trait Test {
    fn mk_pair(self) -> (Self, Self)
    where
        Self: Sized + Clone,
    {
        (self.clone(), self)
    }
}

impl<T> Test for T {}

pub fn testy<T>(x: T) -> (T, T)
where
    T: Clone,
{
    x.mk_pair()
}

Silly example but as you can see I can now call x.mk_pair() instead of mk_pair(x). Probably doesn't matter much in this case but some find method call syntax nice in some cases.

Question is, is this the minimum boilerplate required? The global impl seems a bit hacky. Is there a nicer way to give a function method call syntax without as much trait/impl tomfoolery?

2 Likes

This is a pattern called extension traits, and yes, this is the minimal boilerplate needed.

2 Likes

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.