How to call a function from a standard library:
use std::time::{SystemTime, UNIX_EPOCH}; fn main() { // Get the current system time match SystemTime::now().duration_since(UNIX_EPOCH) { Ok(n) => println!("Current time since UNIX EPOCH: {} seconds", n.as_secs()), Err(_) => println!("SystemTime before UNIX EPOCH!"), } }
How to call a function from a library on Crates.io:
For external libraries, you can specify the external module in the Cargo.toml file.
use regex::Regex;
fn main() {
// Create a regex pattern
let re = Regex::new(r"^\d{4}-\d{2}-\d{2}$").unwrap();
// Test if the pattern matches a string
let date = "2023-10-05";
if re.is_match(date) {
println!("The date {} is in the correct format.", date);
} else {
println!("The date {} is not in the correct format.", date);
}
}
Cargo.toml file content
[dependencies]
regex = "1.5"
Legacy solution for Rust 2015 edition or earlier
On the Rust file you may call extern crate PACKAGE_NAME
to use an external library. This is a handy solution when you want to use Rust Playground like in this example below. Otherwise, you would get an error when you execute the file.
extern crate rand; use rand::Rng; fn main() { // Create a random number generator let mut rng = rand::thread_rng(); // Generate a random number between 1 and 10 let random_number: u32 = rng.gen_range(1..=10); println!("Random number: {}", random_number); }