我目前正在为 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
通过通道在结构中传递 s?
我为那些幼稚的问题道歉。我已经花了很长时间搜索,但我无法完全理解它。这可能是我的动态语言背景妨碍了:)
顺便说一句:是&input[..]
为了将 aString
转换为&str
考虑好的?这是我能找到的唯一稳定的方法。