rust 有"封闭"通道的方法吗,similar to what is available in Go?
其思想是在通道上迭代(持续接收),直到通道指示它不会产生更多的值.
use std::sync::{Arc, Mutex};
use std::thread;
use std::sync::mpsc;
fn main() {
let data = Arc::new(Mutex::new(0u32));
let (tx, rx) = mpsc::channel::<u32>();
{
let (data, tx) = (data.clone(), tx.clone());
thread::spawn(move || {
for _ in 0..10 {
let mut data = data.lock().unwrap();
*data += 1;
tx.send(*data).unwrap();
}
// *** How could I close the channel here, to signal the work is done?
});
}
// *** How can I detect a closed channel here? Pattern matching?
for _ in 0..10 {
let x = rx.recv().unwrap();
println!("{}", x);
}
}