Rust – Package Manager

  • Post author:
  • Post category:Rust
  • Post comments:1 Comment
Rust - Package Manager

Cargo is the Rust Package Manager for RUST. This acts as a tool and manages Rust projects.

Some commonly used cargo commands are listed in the table below −

Sr.NoCommand & Description
1cargo build Compiles the current project.
2cargo check Analyzes the current project and report errors, but don’t build object files.
3cargo runBuilds and executes src/main.rs.
4cargo clean Removes the target directory.
5cargo update Updates dependencies listed in Cargo. lock.
6cargo new Creates a new cargo project.

Cargo helps to download third-party libraries. Therefore, it acts as a package manager. You can also build your own libraries. Cargo is installed by default when you install Rust.

To create a new cargo project, we can use the commands given below.

Create a binary crate

cargo new project_name --bin

Create a library crate

cargo new project_name --lib

To check the current version of cargo, execute the following command −

cargo --version

Illustration – Create a Binary Cargo project

The game generates a random number and prompts the user to guess the number.

Step 1 – Create a project folder

Open the terminal and type the following command cargo new guess-game-app –bin.

This will create the following folder structure.

guess-game-app/
   -->Cargo.toml
   -->src/
      main.rs

The cargo new command is used to create a crate. The –bin flag indicates that the crate being created is a binary crate. Public crates are stored in a central repository called crates.io https://crates.io/.

Step 2 – Include references to external libraries

This example needs to generate a random number. Since the internal standard library does not provide random number generation logic, we need to look at external libraries or crates. Let us use rand crate which is available at crates.io website crates.io

The https://crates.io/crates/rand is a rust library for random number generation. Rand provides utilities to generate random numbers, to convert them to use types and distributions, and some randomness-related algorithms.

The following diagram shows the crate.io website and searches results for the rand crate.

Rust - Package Manager

Copy the version of the rand crate to the Cargo. toml file rand = “0.5.5”.

[package]
name = "guess-game-app"
version = "0.1.0"
authors = ["Mohtashim"]

[dependencies]
rand = "0.5.5"

Step 3: Compile the Project

Navigate to the project folder. Execute the command cargo build on the terminal window −

Updating registry `https://github.com/rust-lang/crates.io-index`
Downloading rand v0.5.5
Downloading rand_core v0.2.2
Downloading winapi v0.3.6
Downloading rand_core v0.3.0
   Compiling winapi v0.3.6
   Compiling rand_core v0.3.0
   Compiling rand_core v0.2.2
   Compiling rand v0.5.5
   Compiling guess-game-app v0.1.0 
   (file:///E:/RustWorks/RustRepo/Code_Snippets/cargo-projects/guess-game-app)
   Finished dev [unoptimized + debuginfo] target(s) in 1m 07s

The rand crate and all transitive dependencies (inner dependencies of rand) will be automatically downloaded.

Step 4 – Understanding the Business Logic

Let us now see how the business logic works for the number guessing game −

  • Game initially generates a random number.
  • A user is asked to enter input and guess the number.
  • If number is less than the generated number, a message “Too low” is printed.
  • If number is greater than the generated number, a message “Too high” is printed.
  • If the user enters the number generated by the program, the game exits.

Step 5 – Edit the main.rs file

Add the business logic to the main.rs file.

use std::io;
extern crate rand; 
//importing external crate
use rand::random;
fn get_guess() -> u8 {
   loop {
      println!("Input guess") ;
      let mut guess = String::new();
      io::stdin().read_line(&mut guess)
         .expect("could not read from stdin");
      match guess.trim().parse::<u8>(){ //remember to trim input to avoid enter spaces
         Ok(v) => return v,
         Err(e) => println!("could not understand input {}",e)
      }
   }
}
fn handle_guess(guess:u8,correct:u8)-> bool {
   if guess < correct {
      println!("Too low");
      false

   } else if guess> correct {
      println!("Too high");
      false
   } else {
      println!("You go it ..");
      true
   }
}
fn main() {
   println!("Welcome to no guessing game");

   let correct:u8 = random();
   println!("correct value is {}",correct);
   loop {
      let guess = get_guess();
      if handle_guess(guess,correct){
         break;
      }
   }
}

Step 6 – Compile and Execute the Project

Execute the command cargo run on the terminal. Make sure that the terminal points to the Project directory.

Welcome to no guessing game
correct value is 97
Input guess
20
Too low
Input guess
100
Too high
Input guess
97
You got it ..

Next Topic – Click Here

This Post Has One Comment

Leave a Reply