- Bilal Khan
- Posts
- Rust Essential: Cargo Package Manager
Rust Essential: Cargo Package Manager
In the last newsletter, I discussed how the Rust compilation and running works.
In this newsletter, I am going to discuss Cargo, a Rust package manager that will make the process of building and running the code by adding the dependencies with its help.
As the project grows, you will want a package manager that can handle all your packages, and dependencies and you can easily download all the libraries for your code.
The majority of the Rust project uses Cargo, and it is installed while installing Rust.
To check, whether the Cargo is installed or not, you can simply write the following command:
$ cargo --version
If you have a version number, it means you have it! If you see an error, such as command not found
then you should install it in your operating system by checking the Rust docs.
Create a Project with Cargo
Now let’s create a new project using cargo and see how it differs from the last Hello World project.
Open the terminal and write the following command for a new package creation:
$ cargo new hello_cargo
$ cd hello_cargo
It creates the following files in the hello_cargo directory:
hello_cargo
│── src
│ │── main.rs # Entry point of the application
│── Cargo.toml # Dependencies & project metadata
│── .gitignore # Ignore files for Git
│── target # Compilation output (ignored in Git)
Below is the text that the Cargo.toml contains:
[package]
name = "hello_cargo"
version = "0.1.0"
edition = "2021"
[dependencies]
The [package] section indicates that the following statements are configuring a package.
The [dependencies] section lists all the libraries or dependencies that are required for the application and you can add them.
Now open the src/main.rs file and it will contain the following code initially:
fn main() {
println!("Hello World!");
}
Building and Running a Cargo project
Now let’s take a look at the difference b/w building and running the Hello World program with Cargo.
$ cargo build
This command will create an executable file inside the target directory (target/debug/hello_cargo).
You can now run this executable by writing the following command:
$ ./target/debug/hello_cargo
If everything goes well, it will print the Hello World message in your terminal.
You can also use the cargo run
command to compile the code and then run the resultant executable all in one command:
$ cargo run
This will print the Hello World message in your terminal.
What's Next?
If you need any Rust guidance and are just curious about learning Rust then you can check out the YouTube playlist “Rust for Beginners“ where I have covered all of the basic concepts in a simple way for you to understand.
If you're interested to learn Rust then I have a 2-month mentorship program for you called Rust for Beginners that will help you build a solid foundation & build amazing projects. Book a FREE call.
Happy Coding!