notify-rs / notify

🔭 Cross-platform filesystem notification library for Rust.
https://docs.rs/notify
2.68k stars 215 forks source link

Type inference RecommendedWatcher #246

Open pickfire opened 4 years ago

pickfire commented 4 years ago

Since there can only be one RecommendedWatcher, why do we still need to explicitly specify the type? Taken from the new docs.

use notify::{Watcher, RecommendedWatcher, RecursiveMode, Result};

fn main() -> Result<()> {
    // Automatically select the best implementation for your platform.
    let mut watcher: RecommendedWatcher = Watcher::new_immediate(|res| {
        match res {
           Ok(event) => println!("event: {:?}", event),
           Err(e) => println!("watch error: {:?}", e),
        }
    })?;

    // Add a path to be watched. All files and directories at that path and
    // below will be monitored for changes.
    watcher.watch(".", RecursiveMode::Recursive)?;

    Ok(())
}

Not sure if we can remove the explicit type for RecommendedWatcher.

passcod commented 4 years ago

You can use the short method with no types:

let mut watcher = immediate_watcher(...)?;

The full form (needs a type hint because Watcher is a trait):

let mut watcher: RecommendedWatcher = Watcher::new_immediate(...)?;

means it's easier to switch implementation:

let mut watcher: INotifyWatcher = Watcher::new_immediate(...)?;

So it might be preferable for demonstration purposes. Otherwise it's just taste.

pickfire commented 4 years ago

Ah, I thought let mut watcher = immediate_watcher(...)?; should be more preferably for a demo to attract attention on the api with shortest code. let mut watcher: INotifyWatcher = Watcher::new_immediate(...)?; may be useful later in the first page, explaining how to switch implementation.