Modules Flashcards
What is crate
Crate is a compilation unit in rust; Crate is compiled to binary ro library
What is cargo
The official Rust package management tool for crates.
What is a module
Logically groups code within a crate.
What is crate.io
The official Rust package registry.
Syntax of a module
//public module
pub mod a_public_module{
pub fn a_public_function(){
} fn a_private_function() { //private function } }
// private module
mod a_private_module {
fn a_private_function() {
}
}
Example defining a module
pub mod movies {
pub fn play(name:String) {
println!(“Playing movie {}”,name);
}
}
fn main(){
movies::play(“Herold and Kumar”.to_string());
}
How to import a module
pub mod movies{
pub fn play(name:String) {
println!(“Playing movie {}”,name);
}
}
use movies::play;
fn main(){
play(“YOU”.to_string());
}
How to do nested modules
pub mod movies {
pub mod english {
pub mod comedy {
pub fn play(name:String) {
println!(“Playing comedy movie {}”,name);
}
}
}
}
use movies::english::comedy::play;
// importing a public module
fn main() {
// short path syntax
play(“Herold and Kumar”.to_string());
play(“The Hangover”.to_string());
//full path syntax
movies::english::comedy::play(“Airplane!”.to_string());
}