我正在Rust写一个文件监视器,我遇到了双重克隆INotify
在spawn
范围内使用它的问题:
fn watch_file(watcher: INotify, path: &String) {
let mut watcher = watcher.clone();
let path = Path::new(path);
let pusher = RedisPusher::new("redis://127.0.0.1/0", "arkona").unwrap();
info!("Watching `{}`", path.as_str().unwrap());
spawn(move || {
let _ = watcher.watch(path, |_, file| {
info!("Change in `{}`", file.path().as_str().unwrap());
file.read_to_string().map(|content| pusher.push(content)).ok();
});
});
}
fn main() {
let args = os::args();
let watcher = INotify::init().unwrap();
for path in args.tail().iter() {
watch_file(watcher.clone(), path);
}
}
我仍在学习Rust,我找不到任何方法将可变观察者作为此方法的值传递。它是唯一的(和惯用的)方式还是有可能最多只能实现一次?
答案 0 :(得分:3)
另一方面,如果你取得参数的所有权(即参数不是参考),你就不会 来声明函数签名中的可变性:
fn add_thing(things: Vec<uint>) -> Vec<uint> {
let mut things = things; // We own this, so we can make it mutable
things.push(1);
things
}
fn main() {
let things = vec![3, 2];
let changed = add_thing(things);
println!("{}", changed);
}
答案 1 :(得分:1)
我刚刚通过@delnan建议解决了这个问题:
fn watch_file(mut watcher: INotify, path: &String)