The correct way to "use" in a macro

I am trying to write a macro that needs to use multiple elements. This is suitable for one use in a file, but to me it seems dirty. Is there a better way to refer directly to elements like impl std::ops::Add for $t or something else? Thanks!

 #[macro_export] macro_rules! implement_measurement { ($($t:ty)*) => ($( // TODO: Find a better way to reference these... use std::ops::{Add,Sub,Div,Mul}; use std::cmp::{Eq, PartialEq}; use std::cmp::{PartialOrd, Ordering}; impl Add for $t { type Output = Self; fn add(self, rhs: Self) -> Self { Self::from_base_units(self.get_base_units() + rhs.get_base_units()) } } impl Sub for $t { type Output = Self; fn sub(self, rhs: Self) -> Self { Self::from_base_units(self.get_base_units() - rhs.get_base_units()) } } // ... others ... )) } 
+5
source share
1 answer

You can either use attribute or refer to it with the full path:

 struct Something { count: i8, } impl std::fmt::Display for Something { fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { write!(f, "{}", self.count) } } 

Note that inside the module, the paths of the element are relative, so you need to either use some super or an absolute path (the best choice, in my opinion):

 mod inner { struct Something { count: i8, } impl ::std::fmt::Display for Something { fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result { write!(f, "{}", self.count) } } } 

There is a middle ground where you use module, but not a dash:

 use std::fmt; impl fmt::Display for Something { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{}", self.count) } } 

And if you are just worried about entering text, you can use the module, but I suppose making it too short, this complicates the understanding:

 use std::fmt as f; impl f::Display for Something { fn fmt(&self, f: &mut f::Formatter) -> f::Result { write!(f, "{}", self.count) } } 
+2
source

All Articles