rust - Restrict lifetime parameter to scope of parameters of a function -


consider 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() { } 

compiling small program fails with:

test.rs:25:5: 25:6 error: `g` not live long enough test.rs:25     g.func();                ^ test.rs:24:41: 26:2 note: reference must valid lifetime 'a defined on block @ 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 valid scope of parameters function @ 24:40 test.rs:24 fn myfunc<'a,t: 'a + mytrait<'a>>(g: t) { test.rs:25     g.func(); test.rs:26 } 

as far understand, lifetime parameter 'a not restricted , arbitrary. however, g parameter , lifetime function scope. therefore not satisfy condition of lifetime 'a in definition of method func.

what want associated type n restricted lifetime of self in mytrait. that's why came explicit lifetime parameter 'a of mytrait. , want function myfunc work, i.e. 'a should somehow restricted lifetime of of parameter g.

what "correct" way solve problem?


a simple example is

struct myptr<'a> {     x: &'a usize }  struct mystruct {     data: vec<usize> }  impl<'a> mytrait<'a> mystruct {     type n = myptr<'a>;      fn func(&'a self) -> self::n {         myptr{x: &self.data[0]}     } } 

note extremely simplified, of course. idea n contains reference contained in mytrait , should therefore never outlive mytrait.

what want not bind generic lifetime, allow "any" lifetime:

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

fully working example in playground


Comments

Popular posts from this blog

php - Wordpress website dashboard page or post editor content is not showing but front end data is showing properly -

How to get the ip address of VM and use it to configure SSH connection dynamically in Ansible -

javascript - Get parameter of GET request -