Install cargo-watch via Cargo or your system package manager, then run cargo watch -x run in your project root to automatically recompile and execute your binary whenever source files change. This tool monitors your filesystem for modifications and triggers a specified command, effectively replacing manual rebuilds during development.
First, install the tool if you haven't already. The easiest method is using cargo install:
cargo install cargo-watch
Once installed, navigate to your project directory and start the watcher. The -x flag tells cargo-watch to execute the command that follows (in this case, run):
cargo watch -x run
By default, cargo-watch monitors all files in the current directory. If you only want to watch specific files or ignore certain directories (like target/ or vendor/), you can create a .cargo-watch.toml configuration file in your project root. This is useful for large projects where recompiling on every minor change is slow.
Here is a practical .cargo-watch.toml example that ignores the target directory and only watches Rust source files:
[watch]
ignore = ["target", "vendor"]
filter_files = ["*.rs"]
[run]
command = "cargo run"
If you need to run a specific binary or pass arguments to your application, you can chain commands directly in the terminal. For example, to run a specific binary named my_app with an argument:
cargo watch -x "run --bin my_app -- --debug"
Note that cargo-watch spawns a new process for each change. If your application holds open file handles or locks that prevent the new binary from starting, you may need to add a delay or use the --clear flag to ensure the previous process terminates cleanly before the new one starts. For most standard CLI tools and web servers, the default behavior works immediately without extra configuration.