Rust is a compiled language, meaning every time we make a code change the project needs to be rebuilt and run. This differs from a scripting language such as PHP or JavaScript, where a change is applied right away without requiring an additional compilation step.
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
Using Cargo
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 bin
directory.
Homebrew
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 run
).
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"