2015-06-27 105 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