Defining tuple methods -



Defining tuple methods -

here's swap function two-element tuples:

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

example use:

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

is there way define swap method on two-element tuples? i.e. may called like:

(10i, 20i).swap()

yes, there is. define new trait , implement immediately, this:

trait swap<u> { fn swap(self) -> u; } impl<a, b> swap<(b, a)> (a, b) { #[inline] fn swap(self) -> (b, a) { allow (a, b) = self; (b, a) } } fn main() { allow t = (1u, 2u); println!("{}", t.swap()); }

note in order utilize method have import swap trait every module want phone call method.

methods tuples rust

Comments

Popular posts from this blog

formatting - SAS SQL Datepart function returning odd values -

c++ - Apple Mach-O Linker Error(Duplicate Symbols For Architecture armv7) -

php - Yii 2: Unable to find a class into the extension 'yii2-admin' -