Ho iniziato con l'esempio per EventLoop dalla pagina web milioni e ha aggiunto la funzione principale:Quale argomento passare e come scoprirne il tipo?
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);
}
Poi ho avuto l'idea di spostare il thread di invio ad una funzione "foo" separato e ha iniziato a chiedersi che tipo è passato:
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);
}
Così, ho lasciato il compilatore mi dica il tipo:
fn foo(s: &String) { ...
genera l'errore:
error: mismatched types:
expected `&collections::string::String`,
found `&mio::event_loop::Sender<_>`
Ok, bello, ma sostituendo &String
dal &mio::event_loop::Sender<u32>
genera l'errore:
error: struct `Sender` is private
fn foo(s: &mio::event_loop::Sender<u32>) {
^
Hm, sembra un vicolo cieco, così ho pensato di passaggio event_loop invece:
fn foo(s: &mio::event_loop::EventLoop<u32>) {
let sender = s.channel().clone();
...
fn main() { ...
foo(&event_loop); ...
ma che solleva l'errore:
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>) {
che mi confonde completamente.
In es. C/C++ Avrei appena passato un puntatore a EventLop o Sender.
What is Rust trying to tell me here? How to get it working in Rust?
Ambiente: rustc 1.0.0 (a59de37e9 2015/05/13) (costruito 2015/05/14), mio 0.3.5
Infatti, definendo _foo_ come 'fn foo (s: & mio :: Sender) {...' e chiamandolo 'foo (& mittente); 'funziona. Grazie! –
Chris
Il compilatore non sarà perfetto per indovinare i tuoi tipi ... Voglio dire, prova a guardare cosa C++ emette quando hai iteratori per un contenitore complesso ... Ho già visto un tipo di 500 caratteri. È utile, ma devi ancora pensarci un po '. Un altro trucco è quando il compilatore di Rust ti dice di usare "core ::" dovresti davvero usare "std ::". – Nashenas