Open In App

Rust – Dependencies

Last Updated : 09 Nov, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

In Rust,  there are situations where we encounter situations where there is a dependency on other libraries. The rust ecosystem has a solution to it by having Cargo as its package manager that eases managing dependencies in almost all situations efficiently.

Syntax:

For creating a new library, we use the following syntax with cargo:

cargo new –lib gfg

Here, we make a new library gfg

 

After we have created the library gfg, we see:

gfg
├── cargo.toml
└── src
   â””── lib.rs
 

 

There is a certain hierarchy that is followed in the rust ecosystem. Here, for this particularly lib.rs is the main root source for our project gfg. Cargo.toml is the default config file for cargo for our project (gfg). Inside the directory, we see the following dependency described:

[package]
name = "gfg"
version = "0.1.0"
edition = "2021"

[dependencies]

The fields described in the dependencies are as follows:

  • name: the name under the package is the name of the project. 
  • version: version refers to the crate version number that is being used in our project
  • edition: refers to the latest released edition.

The [dependencies] section lets us add dependencies for your project as per our requirements.

In this example, we would be a dependency rand in our library that would help in generating a random number.

Example 1:

Rust




use rand::Rng;
fn main() {
    println!("Guessing the two numbers:");
    let mut n=1;  
while n<=3
{  
    let secret_number_one = rand::thread_rng().gen_range(1..=20);
    let secret_number_two = rand::thread_rng().gen_range(1..=20);
    println!("The secret number in {n}th iteration is: {secret_number_one}");
    println!("The secret number in {n}th iteration is: {secret_number_two}");
    n+=1;
    }
     
}


Output:

Before importing rand, we get this error in our output:

 

Rand is a dependency in rust that is used for generating random numbers. Once, rand is included in the cargo dependency, we get the correct output:

[package]
name = "gfg"
version = "0.1.0"
edition = "2021"
[dependencies]
rand = "0.8.5"

Output:

 

Explanation:

In this example, we import the Rng module that has the rand dependency. We use the rand::thread_rng.gen_range between numbers 1 to 20 for two numbers secret_number_one and secret_number_two and then used a while loop for getting the values for three iterations in this case.


Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads