2014-10-14 13 views
6

Alcuni metodi tratto hanno implementazioni predefinite che possono essere sovrascritte da un implementatore. Come posso utilizzare l'implementazione predefinita per una struttura che sovrascrive il valore predefinito?Utilizzo di un metodo tratto predefinito

esempio:

trait SomeTrait { 
    fn get_num(self) -> uint; 
    fn add_to_num(self) -> uint { 
     self.get_num() + 1 
    } 
} 

struct SomeStruct; 
impl SomeTrait for SomeStruct { 
    fn get_num(self) -> uint { 3 } 
    fn add_to_num(self) -> uint { 
     self.get_num() + 2 
    } 
} 

fn main() { 
    let the_struct = SomeStruct; 
    println!("{}", the_struct.add_to_num()): // how can I get this to print 4 instead of 5? 
} 

risposta

5

Ci potrebbe essere una soluzione migliore, ma quello che è venuta in mente è quello di definire solo una struct fittizio che contiene lo struct voglio cambiare, e poi posso Cherry- scegli quali metodi voglio sovrascrivere e quali voglio mantenere come predefinito. Per estendere l'esempio originale:

trait SomeTrait { 
    fn get_num(self) -> uint; 
    fn add_to_num(self) -> uint { 
     self.get_num() + 1 
    } 
} 

struct SomeStruct; 

impl SomeTrait for SomeStruct { 
    fn get_num(self) -> uint { 3 } 
    fn add_to_num(self) -> uint { 
     self.get_num() + 2 
    } 
} 

fn main() { 

    struct SomeOtherStruct { 
     base: SomeStruct 
    } 

    impl SomeTrait for SomeOtherStruct { 
     fn get_num(self) -> uint { 
      self.base.get_num() 
     } 
     //This dummy struct keeps the default behavior of add_to_num() 
    } 

    let the_struct = SomeStruct; 
    println!("{}", the_struct.add_to_num()); 

    //now we can call the default method using the original struct's data. 
    println!("{}", SomeOtherStruct{base:the_struct}.add_to_num()); 
} 
Problemi correlati