Search code examples
rust

How change my code to work with different types?


My block 1 works and I receive: "abc" and 49.
How change my code to make block 2 work instead of block 1 ?

I can't change it to fn f01(&self) -> ; for work.
Mylink

struct Dom {a: String,}
struct Num {a: u8,}

trait Trt {
    fn f01(&self);
}
   
   
    impl Trt for Dom {
        fn f01(&self) {
            
            println!("{:?}", &self.a);
        }
    }
    impl Trt for Num {
        fn f01(&self) {
            
            println!("{:?}", &self.a * &self.a);
        }
    }
fn main() {
   
    let dom = Dom {a: "abc".to_string()};
    let num = Num {a: 7};
    
    // Block 1:
       Trt::f01(&dom);                    // "abc"
       Trt::f01(&num);                    // 49
    
    // Block 2:
    // Trt::f01(&dom);                    // "abc"
    // let b: u8 = Trt::f01(&num) + 1;
    // println!("{:?}", b);               // 50
}

Solution

  • I think you might want to use Associated types here.

    struct Dom {
        a: String,
    }
    struct Num {
        a: u8,
    }
    
    trait Trt {
        // This trait also have a assoiated type 
        type OutputF01;
        // We define that the function f01 will return Self::OutputF01
        fn f01(&self) -> Self::OutputF01;
    }
    
    impl Trt for Dom {
        // For Dom we return nothing
        type OutputF01 = ();
        
        fn f01(&self) -> Self::OutputF01 {
            // just a print statement and no return
            println!("{:?}", self.a);
        }
    }
    impl Trt for Num {
        // For Num we will return an u8
        type OutputF01 = u8;
        fn f01(&self) -> Self::OutputF01 {
            // return the square of self.a
            self.a * self.a
        }
    }
    
    fn main() {
        let dom = Dom {
            a: "abc".to_string(),
        };
        let num = Num { a: 7 };
    
        Trt::f01(&dom); // "abc"
        let b: u8 = Trt::f01(&num) + 1;
        println!("{:?}", b); // 50
    }