How to return a struct with references in rust?

365 Views Asked by At

I'm using crossbeam-epoch to write a lock-free data structure in rust. crossbeam-epoch uses a guard to load the heap-allocated atomic pointer. One example of the data structure's interface is:

fn get(&self, index: IndexType, guard: &'guard Guard) -> Option<&'guard Value>

This method requires a guard which has the same lifetime with the returned value's reference.

Now, I want to wrap this method without providing a Guard. For example:

struct ReturnType<'guard, Value> {
    guard: Guard,
    value: Option<&'guard Value>
}

impl<'guard, Value> MyDataStructure<Value> {
    fn my_get(&self, index: IndexType) -> ReturnType<'guard, Value> {
        let guard = pin();
        let value = self.get(index, &guard);
        ReturnType {
            guard: guard,
            value: value
        }
    }
}

But the compiler won't allow me to do this.

My question is how to implement the method my_get?

1

There are 1 best solutions below

0
On

This question needs some improvement. You should always add a minimal reproducable example and you haven't shown what the compiler error was either.

Anyways, in your code, you just forget to specify what the lifetime should be linked to. If the guard at least lives as long as self, then you should declare your method with:

fn my_get<'guard>(&'guard self, index: IndexType) -> ReturnType<'guard, Value> {

&'guard self tells the compiler to link 'guard to self. If the guard should live longer than the struct then you have to move the Value or if you want to share the reference use Arc<Value> (Documentation)