lifetime of a lambda expression in rust -


if have function returns function:

fn<'r, t> ( p : t ) -> (&'r fn(&'r str) -> ~[(t,int)]) {      return |s| ~[(p, 0)] } 

however, doesn't seem work, following (somewhat tautological) error:

playground.rs:10:8: 10:29 error: cannot infer appropriate lifetime due conflicting requirements playground.rs:10         return |s| ~[(p, 0i)]                          ^~~~~~~~~~~~~~~~~~~~~ playground.rs:9:70: 11:5 note: first, lifetime cannot outlive block @ 9:70... playground.rs:9     pub fn result<'r, t>( p : t ) -> (&'r fn(&'r str) -> ~[(t, int)] ){ playground.rs:10         return |s| ~[(p, 0i)] playground.rs:11     } playground.rs:10:8: 10:29 note: ...due following expression playground.rs:10         return |s| ~[(p, 0i)]                          ^~~~~~~~~~~~~~~~~~~~~ playground.rs:9:70: 11:5 note: but, lifetime must valid lifetime &'r  defined on block @ 9:70... playground.rs:9     pub fn result<'r, t>( p : t ) -> (&'r fn(&'r str) -> ~[(t, int)] ){ playground.rs:10         return |s| ~[(p, 0i)] playground.rs:11     } playground.rs:10:8: 10:29 note: ...due following expression playground.rs:10         return |s| ~[(p, 0i)]                          ^~~~~~~~~~~~~~~~~~~~~ error: aborting due previous error 

i believe saying lifetime of return of function signature , return value don't match up. however, i'm not sure how annotate lambda lifetime make work.

so common mistake in rust, thinking lifetime parameters affect lifetimes.

they not, allow compiler know reference returned function lasts amount of time. true anyway, compiler knows , can allow more code safe. consequence of rust doing local analysis (looking @ single function @ time).

in case, creating stack closure. name suggests, stack closure created on stack , returning stack. similar c code:

int *foo() { int = 5; return &a; } 

clearly, pointer (or "reference") a invalid moment return. rust prevents.

in case, lifetime of stack closure lasts duration of function, lifetime parameter requires last longer (though there nothing how long exactly), hence mismatch error.

a basic rule-of-thumb if have lifetime parameters on function, need each parameter in position in argument list , return type, otherwise doing wrong.

if wish return closure, must use heap closure, ~fn (&str) -> ~[(t, int)], since allocated on heap , can passed around more freely (though still not copied).


Comments

Popular posts from this blog

java.util.scanner - How to read and add only numbers to array from a text file -

rewrite - Trouble with Wordpress multiple custom querystrings -