>

Cargo

Python Virtual Environments allow Python to contain the packages/modules that a Python project might need.

In Rust, we use Cargo and Crates.

Let’s make a new cargo crate.

This tutorial is from “The Book” Chapt. 1 Sub. 3 Hello Cargo!.

cargo new hello_cargo
cd hello_cargo

The first command makes a new crate, the second command changes directories into it.

Cargo also initializes a git repo for us, and a .gitignore.

Some files cargo has made for us:

  • Cargo.toml (the configuration file used to configure the crate, and it’s dependencies)
  • src directory (where all your rust code will live)
  • Within the Src directory a main.rs (src/main.rs)

Cargo.toml is in the TOML (Tom’s Obvious, Minimal Language) format, which is Cargo’s configuration format.

In it will be the name of the crate, the crates version, and the year of the version of rust that was used to make it.

1
2
3
4
5
6
7
8
[package]
name = "hello_cargo"
version = "0.1.0"
edition = "2021"

# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

[dependencies]

It will also list dependencies and have version info for them.

Dependency version allows a crate to not keep worrying about major version changes to any of it’s dependencies. (It will always get the exact versions defined rather than getting the latest)

For a tutorial on dependencies see “The Book” Chapt. 2 Programming a Guessing Game.

1
2
3
4
5
6
7
8
9
[package]
name = "hello_cargo"
version = "0.1.0"
edition = "2021"

# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

[dependencies]
rand = "0.8.5"

For more information about Cargo, check out its documentation.


2023-10-24