我正在用 Rust 编写一个文件观察器,我遇到了双重克隆 INotify
以在 spawn
ed 范围内使用它的问题:
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,我找不到任何方法将可变观察器作为值传递给此方法。这是唯一(且惯用)的方式还是有可能让它最多发生一次?
最佳答案
附带说明一下,如果您获得了参数的所有权(即参数不是引用),则您没有在函数签名中声明可变性:
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);
}
关于clone - 省略传递给函数的双克隆值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27533922/