私は現在、特にチャネルを介して構造体を渡す場合に、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
これが (の 1 回の反復でしか生きられない)理由はわかりますが、これfor
を行う正しい方法が何であるかはわかりません。
- コンパイラが示唆するように、 を に変換する必要
&str
があり&'static str
ますか? 'static
すべての行に寿命がある場合、メモリをリークしていますか?'static
とにかくいつ使用することになっていますか?それは私が避けるべきものですか、それともまったく問題ありませんか?String
チャネル経由で構造体に sを渡すより良い方法はありますか?
素朴な質問で申し訳ありません。すでにかなりの時間をかけて検索しましたが、頭を包み込むことはできません。それはおそらく私の動的言語のバックグラウンドが邪魔をしているのです:)
余談ですが、a を考慮された OK&input[..]
に変換するためのものですか? これは、これを行うために私が見つけることができる唯一の安定した方法です。String
&str