48

I have heard cargo has the ability to automatically recompile changed source files, but I'm having a hard time figuring out how to tell it to do so.

For now, I am manually running cargo build or cargo run every time I want to type check my code. I would prefer to instead simply save the file and see the results in the neighboring terminal window.

In case you still have no idea what I'm talking about, I'm looking for the cargo equivalent of sbt ~compile or sbt ~run.

It seems strangely hard to find, so I'm starting to wonder if it's really supported. It's possible someone had said cargo could detect changed files and recompile them when what he meant to say was that cargo could detect unchanged files and avoid recompiling them, like make.

4

6 回答 6

70

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

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
于 2016-06-30T08:27:23.113 回答
3

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.

于 2015-06-30T19:58:51.857 回答
2

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.

于 2015-04-05T20:14:58.703 回答
1

Another option is using entr

ls -r | entr cargo run

This will recursively list all files in the current directory. Then redirect them to the entr command which watches for changes to those files and then finally runs cargo run

于 2020-07-30T22:41:39.687 回答
0

I use nodemon with this command:

nodemon --watch src -e rs --exec cargo check

All this does is watch all the rs files in the src folder and run cargo check.

于 2021-11-09T09:37:37.080 回答
-4

In you Visual Studio Code : Go to File and check Auto Save which will automatically save the changes made.

于 2020-06-09T11:44:08.360 回答