What is cargo in Rust Language?

Cargo is an official Rust package management tool to create compile and execute Rust applications. It is similar to npm in Nodejs and dart pub in dart/Flutter.

With cargo, you can create the following things

  • dependencies are configured in the toml file
  • download the dependencies from crates.io
  • Compile packages
  • and upload dependencies into crates.io

Create an application with Cargo

To create a Rust project, open the terminal and run the below commands

## Create a Running project
cargo new --bin project

## Create a library project
cargo new library

Let’s create a new project using cargo new command

A:\work\rust>cargo new firstapp
     Created binary (application) `firstapp` package

This command creates a project firstapp, which contains the folder structure of an application created.



│   .gitignore
│   Cargo.lock
│   Cargo.toml
│
├───src
│       main.rs
│
└───target
    │   .rustc_info.json
    │   CACHEDIR.TAG
    │
    └───debug
        │   .cargo-lock
        │   firstapp.d
        │   firstapp.exe
        │   firstapp.pdb
        │
        ├───.fingerprint
        │   └───firstapp-e68389ed46d6bd29
        │           bin-firstapp
        │           bin-firstapp.json
        │           dep-bin-firstapp
        │           invoked.timestamp
        │
        ├───build
        ├───deps
        │       firstapp.d
        │       firstapp.exe
        │       firstapp.pdb
        │
        ├───examples
        └───incremental
            └───firstapp-o4oqw0ldn9i8
                │   s-g8p7jzqdgh-zkc3h7.lock
                │
                └───s-g8p7jzqdgh-zkc3h7-2exf863waqrj1
                        2tf2ot9x0ayv97jm.o
                        3dg6fjtpg4mc8d0e.o
                        3o1fkpoam27106fo.o
                        3wpxon66x8f2ttmx.o
                        47dn1uxiswgfa140.o
                        4q5joxozhhx0br3u.o
                        6igwucj9qi6qaxw.o
                        dep-graph.bin
                        query-cache.bin
                        uo6o7oqfq3u35j7.o
                        work-products.bin

  • src folder: Contains Rust code files, Contains main.rs and other modules files
  • main.rs is Root file, It entry execution file when you run the project using the cargo run command
  • Cargo.toml contains dependencies of a project add the below project metadata.
[package]
name = "firstapp"
version = "0.1.0"
authors = ["w3schools.io"]

# dependencies required for running the project
[dependencies]

# Dependencies required for development
[build-dependencies]

Next, Open the Project to any Editor of your choice

Add the below code to src/main.rs.

// HelloWorld.rc Hello World First example program
// It prints the hello world string to the console

// main function executes when a binary compiled file executed
fn main() {
    // Print string to the console
    println!("Hello World Example First Program");
}

Added Hello World program to a cargo project. Now, It is time to run the application

Next, Run the program using the cargo run command in terminal

A:\work\rust\firstapp>cargo run
    Finished dev [unoptimized + debuginfo] target(s) in 0.01s
     Running `target\debug\firstapp.exe`
Hello World Example First Program

Add the dependencies and run the cargo project

The cargo project has two files for dependencies

  • Cargo.lock
  • Cargo.toml: Contains dependencies You can add in two ways,

One way using the command line with cargo add command

cargo add rand

It adds to Cargo.toml as a dependency, and installs to a local project, updates to Cargo.lock file.

Another way directly add Cargo.toml file

Open Cargo. toml file, add the dependencies.

rand is a library from crates.io to generates a random number, the version is

[dependencies]
rand = "0.8.5" # from crates.io
# githublib = { git = "https://github.com/myapp/lib" } # from github repo
# locallibrary = { path = "../locallibrary" } # from a local system path filesystem

Dependencies can be included in multiple ways

  • You can specific name=version to get dependency from cates.io
  • Specify name={git="url"} to get the dependencies github repository
  • Include local path of an library using {path=“localpath”} to include local dependencies Next, Modify the main.rs to generate random numbers between a range of numbers
use rand::Rng;

fn main() {
    let random_number = rand::thread_rng().gen_range(1..=10);
    println!("Generate Random Number between 1 and 10: {}", random_number);
}

Once, code changes are done, You need to build the project and run it with the below commands.

cargo build
cargo run
A:\work\rust\firstapp>cargo build
   Compiling firstapp v0.1.0 (A:\work\rust\firstapp)
    Finished dev [unoptimized + debuginfo] target(s) in 1.02s

cargo build command: Compiles rust code and dependent code, generates executable output. Locations of the generated files are target/debug

Other Cargo commands

To run unit test cases

cargo test

To generate documentation for aproject

cargo doc --open

To pass command line arguments to cargo

cargo run argument1 argument2

To release library, use the below command.

cargo build --release