How can I get cargo to recompile changed files automatically?

cargo watch

In case you are working on a server project (e.g. hyper, iron, etc) that keeps running and you need it to be restarted when files change, you can use cargo watch. Install:

cargo install cargo-watch

And then run:

cargo watch -x run

And to watch changes in only the src folder and clear the console use:

cargo watch -c -w src -x run

See the cargo-watch README for more examples.

watchexec

Alternatively, you can use watchexec. Install it:

cargo install watchexec-cli

And then use it like this:

watchexec -r cargo run

There doesn't seem to be any support built in, but there is an extension (cargo-watch) to detect changes using inotify.

When I found it, it wouldn't work with stable (or current) Rust, but I've since patched it. It could still use some work, but it certainly speeds up the compile/fix-errors cycle.


I believe that the distinction is that running cargo run twice won't build the code twice, unless the input files have changed. As far as I know, Cargo doesn't have the functionality you want built-in. You could file a feature request. In the meantime, I'd suggest you just use watch. You could also use something like guard. Using watch is simpler, but would just run your code every N seconds. guard would require more setup, but would be a bit more efficient.