Limit the lifetime parameter to the scope of the function parameters

Consider the following example.

trait MyTrait<'a> {
    type N: 'a;

    fn func(&'a self) -> Self::N;
}

fn myfunc<'a,T: 'a + MyTrait<'a>>(g: T) {
    g.func();
}


fn main() {
}

This small program cannot be compiled:

test.rs:25:5: 25:6 error: `g` does not live long enough
test.rs:25     g.func();
               ^
test.rs:24:41: 26:2 note: reference must be valid for the lifetime 'a as defined on the block at 24:40...
test.rs:24 fn myfunc<'a,T: 'a + MyTrait<'a>>(g: T) {
test.rs:25     g.func();
test.rs:26 }
test.rs:24:41: 26:2 note: ...but borrowed value is only valid for the scope of parameters for function at 24:40
test.rs:24 fn myfunc<'a,T: 'a + MyTrait<'a>>(g: T) {
test.rs:25     g.func();
test.rs:26 }

As I understand it, the lifetime parameter 'ais unlimited and can be arbitrary. However, it gis a parameter, and its lifetime is only a domain of functions. Therefore, it does not satisfy the condition of the lifetime 'ain the definition of a method func.

I really want the related type to Nalways be limited to a lifetime selfin MyTrait. Therefore, I came up with an explicit parameter of the lifetime 'a MyTrait. And then I just want the function to myfuncwork, i.e. 'amust be somehow limited by the parameter lifetime g.

"" ?


:

struct MyPtr<'a> {
    x: &'a usize
}

struct MyStruct {
    data: Vec<usize>
}

impl<'a> MyTrait<'a> for MyStruct {
    type N = MyPtr<'a>;

    fn func(&'a self) -> Self::N {
        MyPtr{x: &self.data[0]}
    }
}

, , , . , N -, MyTrait, MyTrait.

+4
1

, "" :

fn myfunc<T: for<'a> MyTrait<'a>>(g: T) {
    g.func();
}

+3

Source: https://habr.com/ru/post/1626177/


All Articles