Rust: Running Code & Tools
Compiling and running
rustc main.rs # compile directly (rarely used)
cargo new my_project # create a new project with Cargo
cd my_project
cargo run # compile and run
cargo build --release # optimized release build
Cargo is Rust's build system and package manager. Almost everyone uses it instead of rustc directly.
Editors
- VS Code -- install the
rust-analyzerextension (the official Rust language server) - CLion + IntelliJ Rust plugin -- JetBrains IDE for Rust
- Vim/Neovim with
rust-analyzerLSP server
Cargo essentials
cargo add serde # add a dependency from crates.io
cargo remove serde # remove a dependency
cargo test # run all tests
cargo test -- --nocapture # run tests with stdout visible
cargo check # fast type-check without producing a binary
cargo clippy # run lints
cargo fmt # auto-format code
Project structure
A Cargo project:
my_project/
Cargo.toml # manifest (name, deps, metadata)
src/
main.rs # entry point for binary
lib.rs # entry point for library
Testing
Tests go in the same file, inside a #[cfg(test)] module:
pub fn add(a: i32, b: i32) -> i32 { a + b }
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_add() {
assert_eq!(add(2, 3), 5);
}
}
Common resources
- The Rust Book -- official, comprehensive, free
- Rust by Example -- learn by doing
- crates.io -- the Rust package registry
- docs.rs -- documentation for every crate
Quick check below!