2014-10-14 13 views
6

Niektóre metody cech mają domyślne implementacje, które można zastąpić przez implementatora. Jak mogę użyć domyślnej implementacji dla struktury, która nadpisuje wartość domyślną?Używanie metody domyślnej domyślnej

przykład:

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

Odpowiedz

5

Nie może być lepszym rozwiązaniem, ale taki mam wymyślić, to po prostu zdefiniować struct atrapę, która zawiera struct I chcesz zmienić, a następnie mogę cherry- wybierz metody, które chcę nadpisać i które chcę zachować jako domyślne. Aby przedłużyć oryginalny przykład:

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()); 
} 
Powiązane problemy