rust - DuplexStream across tasks and closures -
i'm having trouble lifetimes , borrowed points. i've read manual , borrowed pointer tutorial, but... i'm still stuck.
sketch of main.rs
fn main() { let (db_child, repo_child):(duplexstream<~str, ~str>, duplexstream<~str, ~str>) = duplexstream(); spawn { slurp_repos(&repo_child); } }
sketch of repos.rs
fn slurp_repos(chan: &'static duplexstream<~str, ~str>) { ... request.begin |event| { ... chan.send(api_url); } }
when compile these modules, main.rs has following error:
main.rs:21:20: 21:31 error: borrowed value not live long enough main.rs:21 slurp_repos(&repo_child); ^~~~~~~~~~~ note: borrowed pointer must valid static lifetime... main.rs:13:10: 1:0 note: ...but borrowed value valid block @ 13:10 error: aborting due previous error
i can't quite figure out how declare duplexstreams lifetime static. or perhaps wrong way go in function type slurp_repos.
if want see full context:
i'm unable test, guess solution move repo_child
stream slurp_repos
, is:
fn main() { let (db_child, repo_child) = duplexstream(); spawn { slurp_repos(repo_child); } } fn slurp_repos(chan: duplexstream<~str, ~str>) { ... request.begin |event| { ... chan.send(api_url); } }
by moving whole endpoint, allows transferred across tasks (because duplexstream
send
able). also, note sharing (what use of references allows) endpoint of basic bidirectional stream (which duplexstream
is) doesn't make sense: there can 1 person @ each end of telephone.
the error message repo_child
not living long enough because type of slurp_repos
requires 'static
i.e. lasts whole lifetime of program, repo_child
doesn't: local function.
the reason compiler tells put 'static
on slurp_repos
, because send
able reference 1 lifetime. restriction required because have owning task finish before borrowing task does, , destroy/deallocate reference, leaving dangling pointer; in diagrams:
start program/call main | v allocate repo_child | v spawn -----------------> slurp_repos(chan = &repo_child) | | v v finish things chan reference repo_child | | v v deallocate repo_child general work ... | v more things chan: oops, freed; use-after-free bug
Comments
Post a Comment