我目前在 Rust(1.0)中遇到了生命周期的问题,尤其是在通过通道传递结构体时。
我应该如何使这个简单的示例编译通过:
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();
}
}
我理解为:
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...
我能理解为什么会这样(line
只在for
循环的一次迭代中存在),但我想不出正确的做法。
- 按照编译器的提示,我应该尝试将
&str
转换为&'static str
吗? - 如果每行都具有
'static
生命周期,那么我是否会泄漏内存? - 我什么时候应该使用
'static
呢?是应该避免还是完全没问题? - 是否有更好的通过通道传递结构体中的
String
的方法?
对于这些幼稚的问题,我感到抱歉。我已经花了很多时间搜索,但我无法理解。可能是因为我的动态语言背景有些影响 :)
顺便问一下:将String
转换为&str
的&input[..]
是否可行?这是我找到的唯一稳定的方法。
struct
中将&str
替换为String
就可以了。谢谢,我真的应该先尝试一下。 - marekventur