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
Hello world!

If I have another file, such as in the folder:

> tree├──

I can simply switch to run that program:

> rustc 
> ./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:

name = "rs"
version = "0.1.0"
edition = "2021"
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
│ ├──

If we move the 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 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();

Now cargo test should run this new test against the new target hello .


Rust cargo supports a flag bin for us to specify a new target instead of the default main .



Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store