2015-06-27 20 views
5

Sto provando a scrivere una macro che necessita di use alcuni elementi. Questo è adatto per un uso per file, ma mi sembra sporco. C'è un modo migliore per fare riferimento direttamente agli elementi, ad esempio impl std::ops::Add for $t o qualcosa del genere? Grazie!Modo corretto per "utilizzare" in una macro

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

risposta

2

È possibile use il tratto, oppure si può fare riferimento ad esso con il percorso completo:

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

Si noti che all'interno di un modulo, percorsi voce sono relativa, in modo che sia necessario utilizzare un numero di super o di un percorso assoluto (la scelta migliore, a mio parere):

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

C'è una MIDD Le terra dove si use il modulo, ma non il tratto:

use std::fmt; 

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

E se siete solo preoccupato per la digitazione, è possibile alias il modulo, ma è mia convinzione che lo rende troppo breve rende più difficile da capire:

use std::fmt as f; 

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

Il percorso assoluto era esattamente quello che stavo cercando. Grazie! – jocull