Cargo - Intro to Rust 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.
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 :
Let's create our first binary program:
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.
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.
Added dependency will be present in Cargo.toml.
Now let us write some code:
Let's build our first program:
Let's run our first program:
Alternatively, we can run binary programs by simply using the command
Did you find this article valuable?
Support Shreyas K S by becoming a sponsor. Any amount is appreciated!