Trait, struct and leaking mut ref


#1

Hi,

I’m trying to emulate a simple form on inheritance, actually trying to convert some c++ code to rust without changing the structure too much.

I hace a trait and multiple structs implementing it. each of those structs shares couple of methods and some member variables.

in c++ that would be like that, in pseudo code

class MySuperClass {
    int data;
    void do_something_with_data() { // do something useful with data};
}

class MyClass : MySuperClass {...}

I’m trying to replicate a similar structures. here’s the idea.

I have a struct to hold the shared data.

struct MyData {
    data : i32,
}

the trait has some method to have access to this data.

trait MyTrait {
    fn get_data(&mut self) -> &mut MyData;
}

and each struct that implements MyTrait must have their own data and implement the get_gata method.

struct MyStruct {
data : MyData
}

impl MyTrait for MyStruct {
    fn get_data(&mut self) -> &mut MyData
    {
        &mut self.data
    }
}

so far so good, it seems to work…

http://is.gd/Jg1fIK

but… I cannot make it work when MyData is as follow.

http://is.gd/eDA7YX

struct MySharedData;

struct MyData<'a> {
     data : &'a mut MySharedData
}

Would you know how to get this to work? or perhaps there’s a better way to handle shared member variables across struct that implement a same traits.

cheers,

Rémi


#2

I think I found a work around.it seems that returning this “sharedData” is causing me too much pain, so I have shuffle my code so that I do not have to return it…


#3

http://is.gd/OghyEh . The key thing to note here is that the trait needs a lifetime parameter; otherwise, there isn’t any way to express the lifetime parameter of the MyData returned by get_data.


#4

beautiful! I was not aware we could pass a lifetime to a trait. thanks for helping. :slight_smile: