Run multiple targets using Rust cargo
If you have used package.json
from a NodeJS app, you know you can add as many command as you want to support multiple targets (or builds). When I first come to Rust, I have been stuck with rustc
for a while, because I find easy to run any program I want to:
> rustc hello.rs
> ./hello
Hello world!
If I have another file, such as main.rs
in the folder:
> tree├── hello.rs
├── main.rs
I can simply switch to run that program:
> rustc main.rs
> ./main
My style of coding is mostly working with lots of un-related pieces of snippets these days, when I experiment, learn, or blog stuff. Adding a repo or project for them can be deferred to very very late, if needed.
Single target
This process is easy with less overhead. However, it can become difficult in Rust when the program involves dependencies, especially external dependencies. This is where cargo
comes to play, which can be driven by a Cargo.toml
configuration file:
[package]
name = "rs"
version = "0.1.0"
edition = "2021"[dependencies]
assert_cmd = "1"
Given that, we can run various cargo
commands, such as run
to execute the default main
app right away:
> cargo run
This is quite convenient. But what happen to my hello
app with another main
function in it?
fn main() {
println!("Hello world!")
}
More targets
I couldn’t figure out how to add another build line in the Cargo.toml
, at least not yet. However, it seems there’s a secret folder bin
under src
we can specify different target.
> tree srcsrc
├── bin
│ ├── hello.rs
├── main.rs
If we move the hello.rs
under the /src/bin
folder, we can use the same cargo
command to run it:
> cargo run --bin hello
Hello world!
The bin
flag is for us to switch to another target instead of the default main.rs
. Moreover this flag can be used for other cargo
command, such as building for production run:
> cargo build --release --bin hello
You can even run integration test against it if you put a file under tests
folder:
use assert_cmd::Command;#[test]
fn runs() {
let mut cmd = Command::cargo_bin("hello").unwrap();
cmd.assert().success();
}
Now cargo test
should run this new test against the new target hello
.
Conclusion
Rust cargo supports a flag bin
for us to specify a new target instead of the default main
.