Cargo - Intro to Rust Package Manager

Cargo - Intro to Rust Package Manager

Package Manager

The package manager is a collection of related programs which helps in automating the process of installing, obtaining and upgrading artifacts. In a programming language ecosystem, a package manager is a developer-focused tool which assists in downloading library artifacts and their dependency from the language-specific repository.

Cargo-Logo-Small.png In the rust ecosystem, Cargo is the package manager that aid in downloading and compiling packages. Likewise helps in making packages distributable.

Cargo does four things:

  • Introduces two metadata files with various bits of package information.
  • Fetches and builds your package’s dependencies.
  • Invokes rustc or another build tool with the correct parameters to build your package.
  • Introduces conventions to make working with Rust packages easier.

Cargo is installed during rust installation. Alternatively, one can build it from source

Creating A New Package Using Cargo

Open a terminal :

mkdir projects
cd projects

Let's create our first binary program:

Screenshot 2022-09-22 at 11.11.07 AM.png

If we want to create a library package then we can use --lib instead of --bin.

cargo new <name_package> --bin creates a new binary program.

Directory structure:

Screenshot 2022-09-22 at 11.16.06 AM.png

Cargo.toml is a manifest file which contains all the metadata that Cargo needs to compile the package. This file is written in TOML.

Cargo.toml will be having metadata, and dependencies which are required by the package to build and execute.

Adding a dependency to the package: we can use the cargo add command to add a dependency to the package. Alternatively, we can also add dependencies directly into Cargo.toml file under the dependencies section.

Screenshot 2022-09-22 at 11.56.24 AM.png

Added dependency will be present in Cargo.toml.

Screenshot 2022-09-22 at 11.59.26 AM.png

Now let us write some code:

Screenshot 2022-09-22 at 12.10.37 PM.png

Let's build our first program:

Screenshot 2022-09-22 at 12.13.30 PM.png

Let's run our first program:

Screenshot 2022-09-22 at 12.16.05 PM.png

Alternatively, we can run binary programs by simply using the command cargo run.

Screenshot 2022-09-22 at 12.18.36 PM.png

Did you find this article valuable?

Support Shreyas K S by becoming a sponsor. Any amount is appreciated!