0
0
Rustprogramming~5 mins

Using external crates in Rust

Choose your learning style9 modes available
Introduction

External crates let you add ready-made code to your Rust projects. This saves time and helps you do more without writing everything yourself.

You want to use a library for handling dates and times.
You need to make HTTP requests in your program.
You want to add fancy text formatting or colors in the terminal.
You need to work with JSON data easily.
You want to use a math library for complex calculations.
Syntax
Rust
[dependencies]
crate_name = "version"

// In your Rust code:
use crate_name::some_function;

Add external crates in the Cargo.toml file under [dependencies].

Use use in your Rust files to bring crate parts into your code.

Examples
This adds the regex crate version 1.7.0 and imports the Regex type.
Rust
[dependencies]
regex = "1.7.0"

// In your Rust file:
use regex::Regex;
This adds serde with the derive feature to help with serialization.
Rust
[dependencies]
serde = { version = "1.0", features = ["derive"] }

// In your Rust file:
use serde::{Serialize, Deserialize};
Sample Program

This program uses the rand crate to generate a random number between 1 and 10 and prints it.

Rust
[dependencies]
rand = "0.8"

// src/main.rs
use rand::Rng;

fn main() {
    let mut rng = rand::thread_rng();
    let n: u8 = rng.gen_range(1..=10);
    println!("Random number between 1 and 10: {}", n);
}
OutputSuccess
Important Notes

Always run cargo build or cargo run after adding new crates to download and compile them.

Check the crate's documentation for usage details and examples.

Summary

External crates add useful features without extra coding.

Add crates in Cargo.toml and import them in your code.

Use cargo commands to manage and build your project with crates.