Reputation: 1197
While going through Rust by Example, I found myself creating a new cargo project for each program in the tutorial.
This quickly turned cumbersome.
Another strategy I tried was having my working directory structured like this:
src\
guessing_game.rs
main.rs
temp.rs
where main.rs
contains
mod guessing_game;
mod temp;
/// Hello
fn main() {
// guessing_game::play();
println!("{}", temp::is_prime(6));
}
and cargo.toml
contains
[package]
name = "rust_prog_dump"
version = "0.1.0"
edition = "2018"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
rand = "0.8.4"
I would call the target function in main()
and comment out the others.
Do we have an alternative?
I have seen this issue and Jon Cairns' post. I use Windows, hence that script does not work for me.
Upvotes: 1
Views: 2265
Reputation: 42502
Do we have an alternative?
One alternative is to compile by hand using rustc
directly, however that is annoying if you want dependencies.
An other alternative is to have multiple binaries in the crate, then you can select the binary to compile (and run) using --bin
:
> cargo new multibin
Created binary (application) `multibin` package
> cd multibin
> mkdir src/bin
> echo 'fn main() { println!("test 1"); }' > src/bin/test1.rs
> echo 'fn main() { println!("test 2"); }' > src/bin/test2.rs
> echo 'fn main() { println!("primary"); }' >| src/main.rs
> cargo r
error: `cargo run` could not determine which binary to run. Use the `--bin` option to specify a binary, or the `default-run` manifest key.
available binaries: multibin, test1, test2
> cargo r --bin multibin
Compiling multibin v0.1.0 (/private/tmp/multibin)
Finished dev [unoptimized + debuginfo] target(s) in 0.44s
Running `target/debug/multibin`
primary
> cargo r --bin test1
Compiling multibin v0.1.0 (/private/tmp/multibin)
Finished dev [unoptimized + debuginfo] target(s) in 0.10s
Running `target/debug/test1`
test 1
> cargo r --bin test2
Compiling multibin v0.1.0 (/private/tmp/multibin)
Finished dev [unoptimized + debuginfo] target(s) in 0.10s
Running `target/debug/test2`
test 2
As you can see you can have a src/main.rs
which will inherit the crate's name, but usually if you start having multiple binaries you put them all in src/bin
.
A third alternative is to use something like cargo-script
(by far the most convenient but long unmaintained and IIRC only compatible with edition 2015) or runner
or something along those lines (there are probably others).
Upvotes: 3