2015-06-27 104 views
5

我试图编写一个需要use几个项目的宏。这适用于每个文件一次使用,但对我来说感觉很脏。有没有更好的方法直接引用这些项目,例如impl std::ops::Add for $t或其他?谢谢!在宏中使用``的正确方法

#[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 ... 
    )) 
} 

回答

2

您可以use的特质,或者你可以参考它的完整路径:

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) 
    } 
} 

注意,一个模块内,项目路径是相对,所以你要么需要使用一定数量的super或绝对路径(更好的选择,在我看来):

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) 
     } 
    } 
} 

有一个粗粉乐地在那里你use模块,而不是特质:

use std::fmt; 

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

如果你只是担心打字,你可以别名模块,但它是我的信念,使得它太短使得它更难了解:

use std::fmt as f; 

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

绝对路径正是我所期待的。谢谢! – jocull