Running Code Locally with Cargo
If you want to experiment with the code on your own system, then you will need
to first install Rust. Do this by following the
instructions in the Rust Book. This should give you a working rustc
and
cargo
. At the time of writing, the latest stable Rust release has these
version numbers:
% rustc --version
rustc 1.69.0 (84c898d65 2023-04-16)
% cargo --version
cargo 1.69.0 (6e9a83356 2023-04-12)
You can use any later version too since Rust maintains backwards compatibility.
With this in place, follow these steps to build a Rust binary from one of the examples in this training:
-
Click the "Copy to clipboard" button on the example you want to copy.
-
Use
cargo new exercise
to create a newexercise/
directory for your code:$ cargo new exercise Created binary (application) `exercise` package
-
Navigate into
exercise/
and usecargo run
to build and run your binary:$ cd exercise $ cargo run Compiling exercise v0.1.0 (/home/mgeisler/tmp/exercise) Finished dev [unoptimized + debuginfo] target(s) in 0.75s Running `target/debug/exercise` Hello, world!
-
Replace the boiler-plate code in
src/main.rs
with your own code. For example, using the example on the previous page, makesrc/main.rs
look likefn main() { println!("Edit me!"); }
-
Use
cargo run
to build and run your updated binary:$ cargo run Compiling exercise v0.1.0 (/home/mgeisler/tmp/exercise) Finished dev [unoptimized + debuginfo] target(s) in 0.24s Running `target/debug/exercise` Edit me!
-
Use
cargo check
to quickly check your project for errors, usecargo build
to compile it without running it. You will find the output intarget/debug/
for a normal debug build. Usecargo build --release
to produce an optimized release build intarget/release/
. -
You can add dependencies for your project by editing
Cargo.toml
. When you runcargo
commands, it will automatically download and compile missing dependencies for you.
Try to encourage the class participants to install Cargo and use a local editor. It will make their life easier since they will have a normal development environment.