VOOZH about

URL: https://www.geeksforgeeks.org/rust/rust-dependencies/

⇱ Rust - Dependencies - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Rust - Dependencies

Last Updated : 28 Apr, 2025

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

👁 Image
 

After we have created the library gfg, we see:

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

👁 Image
 

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:

Output:

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

👁 Image
 

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:

👁 Image
 

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.

Comment