我有:
use std::collections::{DList, Deque, TreeMap};
use std::comm::{Select, Handle};
fn main() {
let mut list = DList::new();
let mut handles = TreeMap::new();
let select = Select::new();
for i in range(0, 3i) {
// Create channel
let (tx, rx) = channel();
// Move receiver inside dlist
list.push_front(rx);
// Get the mut ref from the dlist
let mut nrx = list.front_mut().unwrap();
let handle = select.handle(nrx);
let id = handle.id();
handles.insert(id, handle);
// Get the mut ref from the map and add to select
unsafe { handles.find_mut(&id).unwrap().add(); }
spawn(proc() {
// Work with the channel
let sender = tx;
});
}
loop {
let selected = select.wait();
println!("Selected channel id: {}", selected);
}
}
我得到的错误是:
<anon>:21:22: 21:40 error: cannot infer an appropriate lifetime for lifetime parameter 'a in function call due to conflicting requirements
<anon>:21 let handle = select.handle(nrx);
^~~~~~~~~~~~~~~~~~
<anon>:21:22: 21:28 note: first, the lifetime must be contained by the expression at 21:21...
<anon>:21 let handle = select.handle(nrx);
^~~~~~
<anon>:21:22: 21:28 note: ...so that automatically reference is valid at the time of borrow
<anon>:21 let handle = select.handle(nrx);
^~~~~~
<anon>:21:36: 21:39 note: but, the lifetime must also be contained by the expression at 21:35...
<anon>:21 let handle = select.handle(nrx);
^~~
<anon>:21:36: 21:39 note: ...so that automatically reference is valid at the time of borrow
<anon>:21 let handle = select.handle(nrx);
^~~
error: aborting due to previous error
playpen: application terminated with error code 101
play.rust-lang链接:http://is.gd/N1cF42。
更改代码以在每个调用try_recv时使用Vec和iter,因为开发人员告诉我select没有为此做好准备(但是?),但想知道哪些是其他解决方案或devs如何处理它。 / p>
答案 0 :(得分:0)
发现此lib https://github.com/mahkoh/comm具有许多通道实现,并且还可以(安全地)选择在编译时未知的通道。来自文档:
use std::thread::{Thread};
use std::old_io::{timer};
use std::time::duration::{Duration};
use comm::{spsc};
use comm::select::{Select, Selectable};
let mut channels = vec!();
for i in 0..10 {
let (send, recv) = spsc::one_space::new();
channels.push(recv);
Thread::spawn(move || {
timer::sleep(Duration::milliseconds(100));
send.send(i).ok();
});
}
let select = Select::new();
for recv in &channels {
select.add(recv);
}
let first_ready = select.wait(&mut [0])[0];
for recv in &channels {
if first_ready == recv.id() {
println!("First ready: {}", recv.recv_sync().unwrap());
return;
}
}