L1 - Beginner
Module System
Libraries and Binaries
src/main.rs
- Binary will be created using thissrc/lib.rs
- Root library moduleAll items in library are private by default. So we need to use
pub
keywordTo use a method from library, we need to provide a absolute path.
// src/lib.rs
pub fn greet() { println!("Hello world");}
// src/main.rs
fn main() { hello::greet();}
The word hello
before the function greet
is the project name specified in Cargo.toml
file
The use
keyword
Helpful to avoid specifying the absolute path everytime a library function is used. Sometimes this is also referred to as importing
use hello::greet;
fn main() { greet();}
Dependencies
- A dependency needs to be added to the
Cargo.toml
file before used - A function from a dependency can be used both in library
src/lib.rs
or binarysrc/main.rs
[package]name = "hello"version = "0.1.0"edition = "2021"
[dependencies]rand = "0.8.5"
We can use absolute path rand::thread_rng().gen_range
use rand::Rng;
fn main() { let x = rand::thread_rng().gen_range(5..9); println!("{}", x);}
or bringing that function to the scope
use rand::Rng;use rand::thread_rng;
fn main() { let x = thread_rng().gen_range(1..100); println!("{}", x);}