Defining tuple methods

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

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

Usage example:

 fn main() { let obj = (10i, 20i); println!("{}", swap(obj)); } 

Is there a way to define swap as a method for two-element tuples? That is, so that it can be called as:

 (10i, 20i).swap() 
+7
methods tuples rust
source share
1 answer

Yes there is. Just define a new characteristic and enter 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 the Swap attribute into each module where you want to call the method.

+7
source share

All Articles