I am currently struggling with a lifetime in Rust (1.0), especially when it comes to passing structures through channels.
How do I get this simple compilation example:
use std::sync::mpsc::{Receiver, Sender}; 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 || { for message in rx.iter() { println!("{}", message.text); } }); let stdin = io::stdin(); for line in stdin.lock().lines() { let message = Message { text: &line.unwrap()[..], }; tx.send(message).unwrap(); } }
I get:
error[E0597]: borrowed value does not live long enough --> src/main.rs:23:20 | 23 | text: &line.unwrap()[..], | ^^^^^^^^^^^^^ does not live long enough ... 26 | } | - temporary value only lives until here | = note: borrowed value must be valid for the static lifetime...
I can see why this is ( line only lives for one iteration of for ), but I cannot figure out how to do it right.
- Should I, like compiler hints, try to convert
&str to &'static str ? - Am I losing memory if each row has a
'static lifetime? - When should I use
'static ? Is this something I should try to avoid or is this normal? - Is there a better way to pass
String in structures through pipes?
I apologize for these naive questions. I spent quite a lot of time searching already, but I can’t completely circle around me. Probably my dynamic language background is interfering :)
Aside: &input[..] for converting a String to &str is considered OK? This is the only stable way I could find for this.
rust channel
marekventur
source share