0
0
Rustprogramming~30 mins

Cargo dependency management in Rust - Mini Project: Build & Apply

Choose your learning style9 modes available
Cargo Dependency Management
📖 Scenario: You are creating a simple Rust project that needs to use an external library to format dates. You will learn how to add and manage dependencies using Cargo, Rust's package manager.
🎯 Goal: Learn how to add a dependency to Cargo.toml, configure its version, use it in your Rust code, and print formatted dates.
📋 What You'll Learn
Create a new Rust project with Cargo
Add the chrono crate as a dependency in Cargo.toml
Use the chrono crate in main.rs to get the current date and time
Print the current date and time in a readable format
💡 Why This Matters
🌍 Real World
Managing dependencies is essential for building Rust applications that use external libraries for tasks like date handling, networking, or data processing.
💼 Career
Understanding Cargo dependency management is a key skill for Rust developers working on real-world projects, ensuring code reuse and easy updates.
Progress0 / 4 steps
1
Create a new Rust project
Use the command cargo new date_formatter in your terminal to create a new Rust project called date_formatter. Then, open the src/main.rs file and write fn main() {} to create an empty main function.
Rust
Hint

Use cargo new date_formatter to create the project, then open src/main.rs and write the main function.

2
Add the chrono dependency
Open the Cargo.toml file and add the line chrono = "0.4" under the [dependencies] section to add the chrono crate version 0.4 as a dependency.
Rust
Hint

Find the [dependencies] section in Cargo.toml and add chrono = "0.4" below it.

3
Use chrono to get current date and time
In src/main.rs, add use chrono::Local; at the top. Inside main(), write let now = Local::now(); to get the current date and time.
Rust
Hint

Import Local from chrono and call Local::now() inside main().

4
Print the formatted current date and time
Add println!("Current date and time: {}", now.format("%Y-%m-%d %H:%M:%S")); inside main() to display the current date and time in the format YYYY-MM-DD HH:MM:SS.
Rust
Hint

Use println! with now.format("%Y-%m-%d %H:%M:%S") to print the date and time.