mardi 19 février 2019

How to use lifetime specifier in decorator pattern in Rust?

I'm new to rust and have not got the lifetime specifier things yet. In order to separate different concerns into different stucts, I try to do something similar to the decorator pattern. However, the following code does not compile:

trait T {
    fn foo(self) -> u64;
}

struct Inner {}

impl T for Inner {
    fn foo(self) -> u64 {
        42
    }
}

struct Outer<'a> {
    delegate: &'a T,
}

impl<'a> T for Outer<'a> {
    fn foo(self) -> u64 {
        self.delegate.foo()
    }
}

pub fn dec_test() {
    let inner = &Inner {};
    let outer = Outer{delegate:inner};

    println!("Meaning of life: {}", outer.foo());
}

I get the following error

error[E0161]: cannot move a value of type dyn decoration_test::T: the size of dyn decoration_test::T cannot be statically determined
--> src/decoration_test.rs:19:9                                                                                     
|                                                                                                                  
19 |         self.delegate.foo()                                                                                      
|         ^^^^^^^^^^^^^                                                                                            

error[E0507]: cannot move out of borrowed content                                                                     
--> src/decoration_test.rs:19:9                                                                                     
|                                                                                                                  
19 |         self.delegate.foo()                                                                                      
|         ^^^^^^^^^^^^^ cannot move out of borrowed content                                                        

error[E0507]: cannot move out of `*self.delegate` which is behind a `&` reference                                     
--> src/decoration_test.rs:19:9                                                                                     
|                                                                                                                  
19 |         self.delegate.foo()                                                                                      
|         ^^^^^^^^^^^^^                                                                                            
|         |                                                                                                        
|         cannot move out of `*self.delegate` which is behind a `&` reference                                      
|         cannot move                                                                                              

error: aborting due to 3 previous errors

Aucun commentaire:

Enregistrer un commentaire