7

Here's a swap function for two-element tuples:

fn swap<A, B>(obj: (A, B)) -> (B, A)
{
    let (a, b) = obj;

    (b, a)
}

Example use:

fn main() {
    let obj = (10i, 20i);

    println!("{}", swap(obj));
}

Is there a way to define swap as a method on two-element tuples? I.e. so that it may be called like:

(10i, 20i).swap()

1 Answer 1

7

Yes, there is. Just define a new trait and implement it immediately, something like this:

trait Swap<U> {
    fn swap(self) -> U;
}

impl<A, B> Swap<(B, A)> for (A, B) {
    #[inline]
    fn swap(self) -> (B, A) {
        let (a, b) = self;
        (b, a)
    }
}

fn main() {
    let t = (1u, 2u);
    println!("{}", t.swap());
}

Note that in order to use this method you will have to import Swap trait into every module where you want to call the method.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.