Cargo
Cargo
If you have been using Ruby for any amount of time, you are familiar with Bundler, Gems, and Gemfiles. Rust has similar concepts.
The Bundler equivalent is called Cargo and is installed via rustup. Gems have an equivalent in Crates. Gemfiles have an equivalent in Cargo.toml files.
Cargo is the Rust package manager. It does more than just manage packages, but for now we’ll introduce it as the way you install the equivalent of Ruby Gems. You can see what version you have installed with: cargo --version.
For example, say we are going to be working with JSON. We would run cargo install serde. Serde is a serialization and deserialization library.
The Ruby equivalent would be bundle install serde. Not surprisingly, a Ruby Gem exists with that name but doesn’t offer the same functionality. That should give you a basic idea of
how Cargo is the equivalent of Bundler.
Crates are the equivalent of Gems. They are libraries and executables you can install on your machine and use in your projects. Crates.io is the canonical source.
Cargo.toml is the equivalent of a Gemfile. It has a corresponding .lock file, just the same as your Ruby’s Gemfile. The toml file lists all of the packages you want to use and claim as dependencies. You can specify versions, paths, etc... Just like in a Gemfiles.
From a high level:
| Rust | Ruby |
|---|---|
| Cargo | Bundler |
| Crates | Gems |
| Cargo.toml | Gemfile |
Now that you have a summary of the Rust equivalent of common Ruby items, let’s take a closer look at Cargo. Cargo offers a lot of functionality.
Cargo allows us to lint our code using cargo clippy. Cargo allows us to run the tests using cargo test. Cargo allows us to format our code using cargo fmt.
As alluded to earlier, it is more than a package manager. Bundler is as well, but Cargo has more functionality in the Rust context, especially when paired with the compiler. The compiler really is wonderful. It’s a shift compared to the runtime-ness of Ruby, but lean into it. Once you get into the flow of utilizing it, it really is quite helpful. Props to everyone that has made the Rust compiler friendly and useful. We’ll take a look at examples in future posts.
Let’s see some of this in action and along the way we’ll spell out the Ruby equivalent for comparison.