Cargo β Bundler + Rake Combined Into One
Gemfile β Cargo.toml, bundle exec β cargo run
Mapping table
| Ruby | Rust (Cargo) | Note |
|---|---|---|
bundle init |
cargo new myproject |
create project |
Gemfile |
Cargo.toml |
dependency definition |
Gemfile.lock |
Cargo.lock |
version lock |
bundle install |
cargo build |
install deps + build |
bundle exec ruby app.rb |
cargo run |
run |
rake test / rspec |
cargo test |
test |
gem build |
cargo build --release |
release build |
gem push |
cargo publish |
publish package |
| RubyGems.org | crates.io | package registry |
| gem | crate | package unit |
Cargo.toml β Ruby's Gemfile
[package]
name = "myproject"
version = "0.1.0"
edition = "2021"
[dependencies]
serde = { version = "1.0", features = ["derive"] }
reqwest = { version = "0.11", features = ["json"] }
tokio = { version = "1", features = ["full"] }
Difference from Gemfile: TOML format, and features let you selectively enable crate functionality. Ruby gems don't have this concept.
cargo commands β frequently used
cargo new myproject # new project (creates Gemfile + directory structure)
cargo build # compile (bundle install + build)
cargo run # build + run
cargo test # run tests
cargo check # type check only (faster than build)
cargo add serde # add dependency (like bundle add serde)
cargo doc --open # generate docs + open in browser
cargo check does type checking without building. Much faster. Useful for checking errors while coding.
Project structure
myproject/
βββ Cargo.toml # dependencies + metadata
βββ Cargo.lock # version lock (should commit)
βββ src/
βββ main.rs # executable entry point
βββ lib.rs # library entry point (optional)
Like Ruby puts code in lib/, Rust uses src/.
Testing β written in the same file
Ruby separates tests in spec/. Rust can put tests in the same file.
// src/lib.rs
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);
}
}
#[cfg(test)] compiles only in test builds. Run with cargo test.
Release build
cargo build --release # optimized binary
# β target/release/myproject
Result is a single binary. No interpreter needed like Ruby. Copy one file to the server and you're done.
Key Points
Gemfile β Cargo.toml, gem β crate, RubyGems β crates.io
cargo run = build + run, cargo check = fast error checking
Tests can be written in the same file with #[cfg(test)]
Release build is a single binary β deploy one file
Pros
- ✓ Dependency management + build + test unified in one tool
- ✓ Build result is single binary β simple deployment
Cons
- ✗ First build is slow β compiles all dependencies
- ✗ target/ directory can grow to several GB