我从mio网页开始使用EventLoop的示例,并添加了主要功能:
extern crate mio;
use std::thread;
use mio::{EventLoop, Handler};
struct MyHandler;
impl Handler for MyHandler {
type Timeout = ();
type Message = u32;
fn notify(&mut self, event_loop: &mut EventLoop<MyHandler>, msg: u32) {
assert_eq!(msg, 123);
event_loop.shutdown();
}
}
fn main() {
let mut event_loop = EventLoop::new().unwrap();
let sender = event_loop.channel();
// Send the notification from another thread
thread::spawn(move || {
let _ = sender.send(123);
});
let _ = event_loop.run(&mut MyHandler);
}
然后我有了将发送线程移动到单独的函数“foo”的想法,并开始想知道传递了什么类型:
extern crate mio;
use std::thread;
use mio::{EventLoop, Handler};
struct MyHandler;
impl Handler for MyHandler {
type Timeout = ();
type Message = u32;
fn notify(&mut self, event_loop: &mut EventLoop<MyHandler>, msg: u32) {
assert_eq!(msg, 123);
event_loop.shutdown();
}
}
fn foo(s: &?) {
let sender = s.clone();
// Send the notification from another thread
thread::spawn(move || {
let _ = sender.send(123);
});
}
fn main() {
let mut event_loop = EventLoop::new().unwrap();
let sender = event_loop.channel();
foo(&sender);
let _ = event_loop.run(&mut MyHandler);
}
所以,我让编译器告诉我类型:
fn foo(s: &String) { ...
引发错误:
error: mismatched types:
expected `&collections::string::String`,
found `&mio::event_loop::Sender<_>`
好的,很好,但&String
替换&mio::event_loop::Sender<u32>
会引发错误:
error: struct `Sender` is private
fn foo(s: &mio::event_loop::Sender<u32>) {
^
嗯,看起来像死路一条,所以我想改为传递event_loop:
fn foo(s: &mio::event_loop::EventLoop<u32>) {
let sender = s.channel().clone();
...
fn main() { ...
foo(&event_loop); ...
但这会引发错误:
error: the trait `mio::handler::Handler` is not implemented for the type `u32` [E0277]
src/main.rs:18 fn foo(s: &mio::event_loop::EventLoop<u32>) {
让我感到困惑。
例如C / C ++我会把一个指针传递给EventLop或Sender。
Rust想告诉我什么?如何让它在Rust工作?
环境:rustc 1.0.0(a59de37e9 2015-05-13)(建于2015-05-14),mio 0.3.5
答案 0 :(得分:5)
Sender
类型将重新导出为mio::Sender
。编译器知道实际类型是mio::event_loop::Sender
并报告。目前无法自动确定您需要的类型,但您可以查看EventLoop::channel
方法的文档,并看到它返回Sender
。如果您点击文档中的Sender
类型,最终会看到mio::Sender