Basic use Statements
mod math {
pub fn add(a: i32, b: i32) -> i32 {
a + b
}
pub fn subtract(a: i32, b: i32) -> i32 {
a - b
}
pub fn multiply(a: i32, b: i32) -> i32 {
a * b
}
}
// Bring individual functions into scope
use math::add;
use math::subtract;
// Or use a grouped import
use math::{add, subtract};
// Or bring everything into scope (not recommended for large modules)
// use math::*;
fn main() {
println!("2 + 3 = {}", add(2, 3));
println!("5 - 2 = {}", subtract(5, 2));
println!("4 * 5 = {}", math::multiply(4, 5)); // Not imported, so we use the full path
}
Renaming with as
use std::io::Result as IoResult;
use std::fmt::Result as FmtResult;
fn io_function() -> IoResult<()> {
// IO operation
Ok(())
}
fn fmt_function() -> FmtResult {
// Formatting operation
Ok(())
}
Nested Paths
// Instead of:
// use std::io;
// use std::io::Write;
// use std::io::Read;
// You can write:
use std::io::{self, Write, Read};
fn main() {
let mut buffer = io::Cursor::new(Vec::new());
buffer.write_all(b"Hello, world!").unwrap();
}
External Crate Dependencies
// Cargo.toml
// [dependencies]
// serde = { version = "1.0", features = ["derive"] }
// serde_json = "1.0"
// In your Rust file:
use serde::{Serialize, Deserialize};
use serde_json;
#[derive(Serialize, Deserialize)]
struct Person {
name: String,
age: u32,
}
fn main() {
let person = Person {
name: String::from("Alice"),
age: 30,
};
let json = serde_json::to_string(&person).unwrap();
println!("JSON: {}", json);
}
The super, self, and crate Keywords
Rust provides special keywords for referring to different parts of the module hierarchy:
self: The Current Module
mod math {
pub fn add(a: i32, b: i32) -> i32 {
a + b
}
pub fn operate(a: i32, b: i32) -> i32 {
// self refers to the current module
self::add(a, b)
}
}
super: The Parent Module
mod parent {
fn private_function() -> i32 {
42
}
pub mod child {
pub fn call_parent() -> i32 {
// super refers to the parent module
super::private_function()
}
}
}
fn main() {
println!("Result: {}", parent::child::call_parent());
}
crate: The Root of the Current Crate
mod deeply {
pub mod nested {
pub mod module {
pub fn function() {
// Absolute path from the crate root
crate::top_level_function();
}
}
}
}
fn top_level_function() {
println!("This is a top-level function");
}
fn main() {
deeply::nested::module::function();
}
Modules and Testing
Rust’s module system interacts with testing in specific ways: