Live Reloading Your Rust Applications
Thankfully, we can use a technique called live reloading to resolve this. We will use cargo-watch to watch for changes made to our source files and then to rerun the binary.
What is Live Reloading?
Live reloading is when a change is detected to a source file, which in turn triggers the application to be rerun. Losing its previous state.
Installing Cargo Watch
If you have the Rust tooling set up on your machine. You can use
cargo install for this.
cargo install cargo-watch
Cargo will build the binary from source and put it inside your
A quicker option for Mac users is that
cargo-watch can be installed using Homebrew.
brew install cargo-watch
Running the Application
Depending on how you have installed Cargo Watch, it'll be callable by either
cargo watch or
cargo-watch. Replace as necessary.
To start watching for file changes that will trigger the application to build and run again. Call Cargo Watch and instruct it to call
run (alias for
cargo watch -x run
Your application should fire up as it usually does. Try making a change to a file and see what happens!
There are several examples of what other things Cargo Watch can do on its Github page. Here are some examples taken from there:
# Run tests only $ cargo watch -x test # Run check then tests $ cargo watch -x check -x test # Run run with arguments $ cargo watch -x 'run -- --some-arg' # Run an arbitrary command $ cargo watch -- echo Hello world # Run with features passed to cargo $ cargo watch --features "foo,bar"