How to Watch for File Changes in Rust (notify crate)

Watch for file changes in Rust using the notify crate to trigger callbacks on events.

Use the notify crate to create a Watcher that listens for events on a specific path and processes them in a callback. Add the dependency, create a watcher, and handle events like Write or Modify to trigger your logic.

use notify::{Config, Event, RecommendedWatcher, Result, Watcher};

fn main() -> Result<()> {
    let mut watcher = RecommendedWatcher::new(
        |res: Result<Event>| {
            if let Ok(event) = res {
                println!("Event: {:?}", event);
            }
        },
        Config::default(),
    )?;

    watcher.watch("./src", notify::RecursiveMode::Recursive)?;
    loop {}
}

Add notify = "6.0" to your Cargo.toml.