PACKAGES, CRATES, MODULES AND PATHS
- A package is a set of crates.
- In a package , we have at most one library crate and zero or more binary crates.
- Library crate are piece of codes that are not executable, they are codes that can be reused among different projects.
- Binary crates are programs you can compile to an executable that you can run.
- A crate is a set of modules.
- A modules is a set of reusable codes.
- Paths is how you refer to modules inside a crate.
- Binary crates can be placed in src bin folder and in this way you can have multiple binary crates inside the same package,
- A new binary create can be created by using below command:
cargo new --bin myapp
- You can create a library crate inside the myapp folder, with below command:
cargo new --lib intutils
- You can go to the lib.rs file in src folder of library crate and add the the following block of code:
pub mod addition{ pub fn add(a: i32, b: i32) -> i32 { a + b } } pun mod subtraction { pub fn sub(a: i32, b: i32) -> i32 { a - b } }
- Then you will need to go to the Cargo.toml file add the crate into it like below:
[package] name = "myapp" version = "0.1.0" edition = "2021" [dependencies] intutils = {path = "intutils"}
- Then you will go to the main.rs in src folder of binary crate and type in normal rust code like below
#![deny(clippy::all)] use intutils::addition::add; use intutils::subtraction::sub; fn main(){ let add1: i32= add(a:3, b:4); let sub1: i32 = sub(a:4, b:4); println!("Add: {}", add1); println!("Sub: {}", sub1); }
Comments
Post a Comment