rust - How do I use static lifetimes with threads? -
i'm struggling lifetimes in rust (1.0), when comes passing struct
s via channel
s.
how simple example compile:
use std::sync::mpsc::{sender, receiver}; use std::sync::mpsc; use std::thread::spawn; use std::io; use std::io::prelude::*; struct message<'a> { text: &'a str } fn main() { let (tx, rx): (sender<message>, receiver<message>) = mpsc::channel(); let handle_receive = spawn(move || { message in rx.iter() { println!("{}", message.text); } }); let stdin = io::stdin(); line in stdin.lock().lines() { let message = message {text: &line.unwrap()[..]}; tx.send(message).unwrap(); } }
i get:
main.rs:62:39: 62:52 error: borrowed value not live long enough main.rs:62 let message = message {text: &line.unwrap()[..]}; ^~~~~~~~~~~~~ note: reference must valid static lifetime... main.rs:62:58: 64:6 note: ...but borrowed value valid block suffix following statement 0 @ 62:57 main.rs:62 let message = message {text: &line.unwrap()[..]}; main.rs:63 tx.send(message).unwrap(); main.rs:64 } error: aborting due previous error
i can see why (line
lives 1 iteration of "for"), can't figure out right way of doing is.
- should i, compiler hints, try convert
&str
&'static str
? - am leaking memory if every line have static lifetime?
- when supposed use
'static
anyway? should try avoid or ok? - is there better way of passing strings in structs via channels?
i apologise naive questions. i've spent quite time googling already, can't quite wrap head around it. it's dynamic language background getting in way :)
as aside: &input[..]
converting string
&str
considered ok? it's stable way find this.
you can't convert &'a t
&'static t
except leaking memory. luckily, not necessary @ all. there no reason send borrowed pointers thread , keep lines on main thread. don't need lines on main thread. send lines themselves, i.e. send string
.
if access multiple threads was necessary (and don't want clone), use arc<string>
(in future, arc<str>
may work). way string shared between threads, properly shared, deallocated when no thread uses more.
sending non-'static
references between threads unsafe because never know how long other thread keep using it, don't know when borrow expires , object can freed. note scoped threads don't have problem (which aren't in 1.0 being redesigned speak) allow this, regular, spawn
ed threads do.
'static
not should avoid, fine does: denoting value lives entire duration program running. if not you're trying convey, of course wrong tool.
Comments
Post a Comment