In real life applications, most of the times we have to pass variable bindings to other functions or assign them to other variable bindings. In this case, we are referencing the original binding; borrow the data of it.
What is Borrowing?
Borrow (verb) To receive something with the promise of returning it.
Shared & Mutable borrowings
βοΈ There are two types of Borrowing,
Shared Borrowing(&T)
A piece of data can be borrowed by a single or multiple users, but data should not be altered.
Mutable Borrowing(&mut T)
A piece of data can be borrowed and altered by a single user, but the data should not be accessible for any other users at that time.
Rules for borrowings
There are very important rules regarding borrowing,
One piece of data can be borrowed either as a shared borrow or as a mutable borrow at a given time. But not both at the same time.
Borrowing applies for both copy types and move types.
The concept of Liveness β΄
fnmain(){
+letmuta=vec![1,2,3];
+letb=&muta;// &mut borrow of `a` starts here
+// β
+// some code // β
+// some code // β
+}// &mut borrow of `a` ends here
+
+
+fnmain(){
+letmuta=vec![1,2,3];
+letb=&muta;// &mut borrow of `a` starts here
+// some code
+
+println!("{:?}",a);// trying to access `a` as a shared borrow, so giving an error
+}// &mut borrow of `a` ends here
+
+
+fnmain(){
+letmuta=vec![1,2,3];
+{
+letb=&muta;// &mut borrow of `a` starts here
+// any other code
+}// &mut borrow of `a` ends here
+
+println!("{:?}",a);// allow borrowing `a` as a shared borrow
+}
+
π‘ Letβs see how to use shared and mutable borrowings in examples.
\ No newline at end of file
diff --git a/docs/docs/cargo-crates-and-basic-project-structure/index.html b/docs/docs/cargo-crates-and-basic-project-structure/index.html
new file mode 100644
index 0000000..f16c8c2
--- /dev/null
+++ b/docs/docs/cargo-crates-and-basic-project-structure/index.html
@@ -0,0 +1,36 @@
+Cargo, Crates and Basic Project Structure Β· Learning Rust
+
Cargo is Rustβs built-in package manager and build system. It also supports the following actions,
Command
Action
cargo new
Create a new project
cargo init
Create a new project in an existing directory
cargo check
Verify the project compiles without errors
cargo build
Build the executable
cargo run
Build the executable and run
π‘ The cargo check command verifies that the project compiles without errors, without producing an executable.
+Thus, it is often faster than cargo build.
π‘ Cargo places executables compiled with cargo build or cargo run in the target/debug/ directory.
+But, while those built with cargo build --release for release purposes are stored in target/release/ directory.
+Release builds use more optimizations and remove some runtime safety checks to increase performance, although this comes at the cost of longer compile time.
Command
Action
cargo add
Add a dependency crate to the project
cargo remove
Remove a dependency crate from the project
cargo fetch
Download the dependencies specified in Cargo.lock
cargo update
Update project dependencies
π‘ A crate is a package that can be shared via crates.io, Rust communityβs crate registry.
+cargo add, cargo remove, cargo fetch, and cargo update commands manage project dependencies through the crate hosted on crates.io.
π‘ The cargo add command includes a specified crate in the [dependencies] section of Cargo.toml, while cargo add --dev adds a crate to the [dev-dependencies] section. This indicates that the crate is only used for development purposes like testing and will not be included in the final compiled code.
Integration tests go in the tests directory (unit tests go in each file they’re testing).
Benchmarks go in the benches directory.
Examples go in the examples directory.
Rust Editions
Rust guarantees backward compatibility while introducing major updates to the language. To support this, the edition field was added to the Cargo.toml file in Rust 2018, marking the first major update to the language ecosystem three years after its initial release. Editions are opt-in, meaning existing crates will not experience these changes until they explicitly migrate to the new edition.
The major editions of Rust are:
Rust 2015: The initial edition, introduced with Rust 1.0. It established the core language features like ownership, borrowing, and lifetimes, laying the foundation for Rustβs safety and concurrency guarantees.
Rust 2018: The first major update, introduced the edition field in Cargo.toml, simplified the module system, stabilized async/await, improved error handling with the ? operator, and made several syntactic changes.
Rust 2021: Focused on improving ergonomics and removing inconsistencies, such as disjoint closure capture, IntoIterator for arrays, and the introduction of or-patterns in macros.
Rust 2024: The latest edition, includes enhancements like refined async features, more const generics, better diagnostics, and improved Cargo features.
For new projects created by cargo new, it will set edition = "2024" by default in the Cargo.toml file. For example,
The .cargo/bin directory of your home directory is the default location of Rust binaries. Not only the official binaries like rustc, cargo, rustup, rustfmt, rustdoc, rust-analyzer and also the binaries you can install via cargo install command, will be stored in this directory.
Even though the initial convention for naming crates and file names is using the snake_case, some crate developers are using kebab-case on both crates and file names. To make your code more consistent, use the initial convention snake_case; especially on file names.
Create an executable crate via cargo new command and run it via cargo run.
Create a library crate via cargo new command and run cargo test.
\ No newline at end of file
diff --git a/docs/docs/code-organization/index.html b/docs/docs/code-organization/index.html
new file mode 100644
index 0000000..ccb5830
--- /dev/null
+++ b/docs/docs/code-organization/index.html
@@ -0,0 +1,5 @@
+Code Organization Β· Learning Rust
+
When a single code block is getting larger, it should be decomposed into smaller pieces and should be organized in a proper manner. Rust supports different levels of code organization.
1. Functions
2. Modules
Can be mapped to a,
Inline module
File
Directory hierarchy
3. Crates
Can be mapped to a,
lib.rs file on the same executable crate
Dependency crate specified on Cargo.toml
Can be specified from,
Path
Git repository
crates.io
4. Workspaces
Helps to manage multiple crates as a single project.
Letβs discuss one by one.
π‘ To make examples more simpler, we use a simple function which prints βHello, world!β. But regarding writing testable codes, always try to return the String from the function and print it when calling it, instead of printing the String inside the function.
\ No newline at end of file
diff --git a/docs/docs/combinators/index.html b/docs/docs/combinators/index.html
new file mode 100644
index 0000000..c656c28
--- /dev/null
+++ b/docs/docs/combinators/index.html
@@ -0,0 +1,189 @@
+Combinators Β· Learning Rust
+
One meaning of βcombinatorβ is a more informal sense referring to the combinator pattern, a style of organizing libraries centered around the idea of combining things. Usually there is some type T, some functions for constructing βprimitiveβ values of type T, and some βcombinatorsβ which can combine values of type T in various ways to build up more complex values of type T. The other definition is “function with no free variables”.
+__ wiki.haskell.org
A combinator is a function which builds program fragments from program fragments; in a sense the programmer using combinators constructs much of the desired program automatically, rather that writing every detail by hand.
+__ John HughesβGeneralizing Monads to Arrows via Functional Programming Concepts
The exact definition of “combinators” in Rust ecosystem is bit unclear.Β
or(), and(), or_else(), and_then()
Combine two values of type T and return same type T.
filter() for Option types
Filter type T by using a closure as a conditional function
Return same type T
map(), map_err()
Convert type T by applying a closure.
The data type of the value inside T can be changed.
+ex. Some<&str> can be converted to Some<usize> or Err<&str> to Err<isize> and etc.
map_or(), map_or_else()
Transform type T by applying a closure & return the value inside type T.
For None and Err, a default value or another closure is applied.
ok_or(), ok_or_else() for Option types
Transform Option type into a Result type.
as_ref(), as_mut()
Transform type T into a reference or a mutable reference.
or() and and()
While combining two expressions, which return either Option/ Result
or(): If either one got Some or Ok, that value returns immediately.
and(): If both got Some or Ok, the value in the second expression returns. If either one got None or Err that value returns immediately.
fnmain(){
+lets1=Some("some1");
+lets2=Some("some2");
+letn: Option<&str>=None;
+
+leto1: Result<&str,&str>=Ok("ok1");
+leto2: Result<&str,&str>=Ok("ok2");
+lete1: Result<&str,&str>=Err("error1");
+lete2: Result<&str,&str>=Err("error2");
+
+assert_eq!(s1.or(s2),s1);// Some1 or Some2 = Some1
+assert_eq!(s1.or(n),s1);// Some or None = Some
+assert_eq!(n.or(s1),s1);// None or Some = Some
+assert_eq!(n.or(n),n);// None1 or None2 = None2
+
+assert_eq!(o1.or(o2),o1);// Ok1 or Ok2 = Ok1
+assert_eq!(o1.or(e1),o1);// Ok or Err = Ok
+assert_eq!(e1.or(o1),o1);// Err or Ok = Ok
+assert_eq!(e1.or(e2),e2);// Err1 or Err2 = Err2
+
+assert_eq!(s1.and(s2),s2);// Some1 and Some2 = Some2
+assert_eq!(s1.and(n),n);// Some and None = None
+assert_eq!(n.and(s1),n);// None and Some = None
+assert_eq!(n.and(n),n);// None1 and None2 = None1
+
+assert_eq!(o1.and(o2),o2);// Ok1 and Ok2 = Ok2
+assert_eq!(o1.and(e1),e1);// Ok and Err = Err
+assert_eq!(e1.and(o1),e1);// Err and Ok = Err
+assert_eq!(e1.and(e2),e1);// Err1 and Err2 = Err1
+}
+
π Rust nightly support xor() for Option types, which returns Some only if one expression got Some, but not both.
or_else()
Similar to or(). The only difference is, the second expression should be a closure which returns same type T.
fnmain(){
+// or_else with Option
+lets1=Some("some1");
+lets2=Some("some2");
+letfn_some=||Some("some2");// similar to: let fn_some = || -> Option<&str> { Some("some2") };
+
+letn: Option<&str>=None;
+letfn_none=||None;
+
+assert_eq!(s1.or_else(fn_some),s1);// Some1 or_else Some2 = Some1
+assert_eq!(s1.or_else(fn_none),s1);// Some or_else None = Some
+assert_eq!(n.or_else(fn_some),s2);// None or_else Some = Some
+assert_eq!(n.or_else(fn_none),None);// None1 or_else None2 = None2
+
+// or_else with Result
+leto1: Result<&str,&str>=Ok("ok1");
+leto2: Result<&str,&str>=Ok("ok2");
+letfn_ok=|_|Ok("ok2");// similar to: let fn_ok = |_| -> Result<&str, &str> { Ok("ok2") };
+
+lete1: Result<&str,&str>=Err("error1");
+lete2: Result<&str,&str>=Err("error2");
+letfn_err=|_|Err("error2");
+
+assert_eq!(o1.or_else(fn_ok),o1);// Ok1 or_else Ok2 = Ok1
+assert_eq!(o1.or_else(fn_err),o1);// Ok or_else Err = Ok
+assert_eq!(e1.or_else(fn_ok),o2);// Err or_else Ok = Ok
+assert_eq!(e1.or_else(fn_err),e2);// Err1 or_else Err2 = Err2
+}
+
and_then()
Similar to and(). The only difference is, the second expression should be a closure which returns same type T.
fnmain(){
+// and_then with Option
+lets1=Some("some1");
+lets2=Some("some2");
+letfn_some=|_|Some("some2");// similar to: let fn_some = |_| -> Option<&str> { Some("some2") };
+
+letn: Option<&str>=None;
+letfn_none=|_|None;
+
+assert_eq!(s1.and_then(fn_some),s2);// Some1 and_then Some2 = Some2
+assert_eq!(s1.and_then(fn_none),n);// Some and_then None = None
+assert_eq!(n.and_then(fn_some),n);// None and_then Some = None
+assert_eq!(n.and_then(fn_none),n);// None1 and_then None2 = None1
+
+// and_then with Result
+leto1: Result<&str,&str>=Ok("ok1");
+leto2: Result<&str,&str>=Ok("ok2");
+letfn_ok=|_|Ok("ok2");// similar to: let fn_ok = |_| -> Result<&str, &str> { Ok("ok2") };
+
+lete1: Result<&str,&str>=Err("error1");
+lete2: Result<&str,&str>=Err("error2");
+letfn_err=|_|Err("error2");
+
+assert_eq!(o1.and_then(fn_ok),o2);// Ok1 and_then Ok2 = Ok2
+assert_eq!(o1.and_then(fn_err),e2);// Ok and_then Err = Err
+assert_eq!(e1.and_then(fn_ok),e1);// Err and_then Ok = Err
+assert_eq!(e1.and_then(fn_err),e1);// Err1 and_then Err2 = Err1
+}
+
filter()
π‘ Usually in programming languages filter functions are used with arrays or iterators to create a new array/ iterator by filtering own elements via a function/ closure. Rust also provides filter()as an iterator adaptor to apply a closure on each element of an iterator to transform it into another iterator. However in here we are talking about the functionality of filter() with Option types.
The same Some type is returned, only if we pass a Some value and the given closure returned true for it. None is returned, if None type passed or the closure returned false. The closure uses the value inside Some as an argument. Still Rust support filter() only for Option types.
fnmain(){
+lets1=Some(3);
+lets2=Some(6);
+letn=None;
+
+letfn_is_even=|x: &i8|x%2==0;
+
+assert_eq!(s1.filter(fn_is_even),n);// Some(3) -> 3 is not even -> None
+assert_eq!(s2.filter(fn_is_even),s2);// Some(6) -> 6 is even -> Some(6)
+assert_eq!(n.filter(fn_is_even),n);// None -> no value -> None
+}
+
map() and map_err()
π‘ Usually in programming languages map() functions are used with arrays or iterators, to apply a closure on each element of the array or iterator. Rust also provides map()as an iterator adaptor to apply a closure on each element of an iterator to transform it into another iterator. However in here we are talking about the functionality of map() with Option and Result types.
map() : Convert type T by applying a closure. The data type of Some or Ok blocks can be changed according to the return type of the closure. Convert Option<T> to Option<U>, Result<T, E> to Result<U, E>
β Via map(), only Some and Ok values are getting changed. No affect to the values inside Err (None doesnβt contain any value at all).
map_err() for Result types : The data type of Err blocks can be changed according to the return type of the closure. Convert Result<T, E> to Result<T, F>.
β Via map_err(), only Err values are getting changed. No affect to the values inside Ok.
Hope you remember the functionality of unwrap_or() and unwrap_or_else() functions. These functions also bit similar to them. But map_or() and map_or_else() apply a closure on Some and Ok values and return the value inside type T.
map_or() : Support only for Option types (not supporting Result). Apply the closure to the value inside Some and return the output according to the closure. The given default value is returned for None types.
map_or_else() : Support for both Option and Result types (Result still nightly only). Similar to map_or() but should provide another closure instead a default value for the first parameter.
β None types doesnβt contain any value. So no need to pass anything to the closure as input with Option types. But Err types contain some value inside it. So default closure should able to read it as an input, while using this with Result types.
#![feature(result_map_or_else)]// enable unstable library feature 'result_map_or_else' on nightly
+fnmain(){
+lets=Some(10);
+letn: Option<i8>=None;
+
+letfn_closure=|v: i8|v+2;
+letfn_default=||1;// None doesn't contain any value. So no need to pass anything to closure as input.
+
+assert_eq!(s.map_or_else(fn_default,fn_closure),12);
+assert_eq!(n.map_or_else(fn_default,fn_closure),1);
+
+leto=Ok(10);
+lete=Err(5);
+letfn_default_for_result=|v: i8|v+1;// Err contain some value inside it. So default closure should able to read it as input
+
+assert_eq!(o.map_or_else(fn_default_for_result,fn_closure),12);
+assert_eq!(e.map_or_else(fn_default_for_result,fn_closure),6);
+}
+
ok_or() and ok_or_else()
As mentioned earlier, ok_or(), ok_or_else() transform Option type into Result type. Some to Ok and None to Err.
ok_or() : A default Err message should pass as argument.
π As mentioned earlier, these functions are used to borrow type T as a reference or as a mutable reference.
as_ref() : Convert Option<T> to Option<&T> and Result<T, E> to Result<&T, &E>
as_mut() : Converts Option<T> to Option<&mut T> and Result<T, E> to Result<&mut T, &mut E>
\ No newline at end of file
diff --git a/docs/docs/comments-and-documenting-the-code/index.html b/docs/docs/comments-and-documenting-the-code/index.html
new file mode 100644
index 0000000..b061ed6
--- /dev/null
+++ b/docs/docs/comments-and-documenting-the-code/index.html
@@ -0,0 +1,42 @@
+Comments and Documenting the code Β· Learning Rust
+
π‘ By convention, try to avoid using block comments. Use line comments instead.
Doc Comments
As we discussed, we can generate the project documentation via rustdoc by running the cargo doc command. It uses the doc comments to generate the documentation.
π‘ Usually we are adding doc comments on library crates. Also, we can use Markdown notations inside the doc comments.
/// Line comments; document the next item
+/** Block comments; document the next item */
+
+//! Line comments; document the enclosing item
+/*! Block comments; document the enclosing item !*/
+
π An attribute is a general, free-form metadatum that is interpreted according to the name, convention, language and compiler version. Any item declaration may have an attribute applied to it. Syntax:
Outer attribute: #[attr]
Inner attribute: #![attr]
π¨βπ« Before going to the next…
Use //! only to write crate-level documentation, nothing else. When using mod blocks, use /// outside of the block. Check the usage of //! and /// doc comments of few popular crates on crates.io. For example, check serde/src/lib.rs and rand/src/lib.rs.
Run cargo new hello_lib --lib command to create a sample crate and replace its src/lib.rs file with the following code. Then run cd hello_lib && cargo doc --open to generate the documentation and open it from your web browser.
//! A Simple Hello World Crate
+
+/// This function returns the greeting; Hello, world!
+pubfnhello()-> String{
+("Hello, world!").to_string()
+}
+
+#[cfg(test)]
+modtests{
+usesuper::hello;
+
+#[test]
+fntest_hello(){
+assert_eq!(hello(),"Hello, world!");
+}
+}
+
\ No newline at end of file
diff --git a/docs/docs/control-flows/index.html b/docs/docs/control-flows/index.html
new file mode 100644
index 0000000..c11b8c5
--- /dev/null
+++ b/docs/docs/control-flows/index.html
@@ -0,0 +1,202 @@
+Control Flows Β· Learning Rust
+
// i. A simple example
+letteam_size=7;
+
+ifteam_size<5{
+println!("Small");
+}elseifteam_size<10{
+println!("Medium");// The code prints this
+}else{
+println!("Large");
+}
+
// ii. Let's refactor above code
+letteam_size=7;
+letteam_size_in_text;
+
+ifteam_size<5{
+team_size_in_text="Small";
+}elseifteam_size<10{
+team_size_in_text="Medium";
+}else{
+team_size_in_text="Large";
+}
+
+println!("Current team size : {}",team_size_in_text);// Current team size : Medium
+
// iii. Let's refactor further
+letteam_size=7;
+letteam_size=ifteam_size<5{
+"Small"// βοΈ no ;
+}elseifteam_size<10{
+"Medium"
+}else{
+"Large"
+};
+
+println!("Current team size : {}",team_size);// Current team size : Medium
+
βοΈ Return data type should be the same on each block when using this as an expression.
match
lettshirt_width=20;
+lettshirt_size=matchtshirt_width{
+16=>"S",// check 16
+17|18=>"M",// check 17 and 18
+19..=21=>"L",// check from 19 to 21 (19,20,21)
+22=>"XL",
+_=>"Not Available",
+};
+
+println!("{}",tshirt_size);// L
+
letis_allowed=false;
+letlist_type=matchis_allowed{
+true=>"Full",
+false=>"Restricted"
+// no default/ _ condition can be skipped
+// Because data type of is_allowed is boolean and all possibilities checked on conditions
+};
+
+println!("{}",list_type);// Restricted
+
letmarks_paper_a: u8=25;
+letmarks_paper_b: u8=30;
+
+letoutput=match(marks_paper_a,marks_paper_b){
+(50,50)=>"Full marks for both papers",
+(50,_)=>"Full marks for paper A",
+(_,50)=>"Full marks for paper B",
+(x,y)ifx>25&&y>25=>"Good",
+(_,_)=>"Work hard"
+};
+
+println!("{}",output);// Work hard
+
loop
loop{
+println!("Loop forever!");
+}
+
// Usage of break and continue
+letmuta=0;
+
+loop{
+ifa==0{
+println!("Skip Value : {}",a);
+a+=1;
+continue;
+}elseifa==2{
+println!("Break At : {}",a);
+break;
+}
+
+println!("Current Value : {}",a);
+a+=1;
+}
+
// Working with arrays/vectors
+letgroup: [&str;4]=["Mark","Larry","Bill","Steve"];
+
+fornin0..group.len(){// group.len() = 4 -> 0..4 π check group.len() on each iteration
+println!("Current Person : {}",group[n]);
+}
+
+forpersoningroup.iter(){// π group.iter() turn the array into a simple iterator
+println!("Current Person : {}",person);
+}
+
+for(index,person)ingroup.iter().enumerate(){// π‘ group.iter().enumerate() helps to read both the current index (starting from zero) and the value
+println!("Person {} : {}",index,person);
+}
+
\ No newline at end of file
diff --git a/docs/docs/crates/index.html b/docs/docs/crates/index.html
new file mode 100644
index 0000000..30b47b1
--- /dev/null
+++ b/docs/docs/crates/index.html
@@ -0,0 +1,201 @@
+Crates Β· Learning Rust
+
π Crates are a bit similar to the packages in some other languages. Crates compile individually. If the crate has child file modules, those files will get merged with the crate file and compile as a single unit.
π A crate can produce an executable/ a binary or a library. src/main.rs is the crate root/ entry point for a binary crate and src/lib.rs is the entry point for a library crate.
01. lib.rs on executable crate
π‘ When writing binary crates, we can move the main functionalities to src/lib.rs and use it as a library from src/main.rs. This pattern is quite common on executable crates.
π― As I mentioned earlier, in here we use simplest examples to reduce the complexity of learning materials. But this is how we need to write greetings/src/lib.rs to make the code more testable.
// greetings/src/lib.rs
+pubfnhello()-> String{
+//! This returns `Hello, world!` String
+("Hello, world!").to_string()
+}
+
+// 01. Tests for `hello()`
+#[test]// Indicates that this is a test function
+fntest_hello(){
+assert_eq!(hello(),"Hello, world!");
+}
+
+// 02. Tests for `hello()`, Idiomatic way
+#[cfg(test)]// Only compiles when running tests
+modtests{// Separates tests from code
+usesuper::hello;// Import root `hello()` function
+
+#[test]
+fntest_hello(){
+assert_eq!(hello(),"Hello, world!");
+}
+}
+
π When importing a crate that has dashes in its name βlike-thisβ, which is not a valid Rust identifier, it will be converted by changing the dashes to underscores, so you would write extern crate like_this;
lib.rs can link with multiple files.
// # Think we run,
+cargonewphrases
+touchphrases/src/lib.rs
+touchphrases/src/greetings.rs
+
+// # It generates,
+phrases
+βββCargo.toml
+βββsrc
+βββgreetings.rs
+βββlib.rs
+βββmain.rs
+
+// # Think we modify following files,
+
+// 01. phrases/src/greetings.rs
+pubfnhello(){
+println!("Hello, world!");
+}
+
+// 02. phrases/src/main.rs
+externcratephrases;
+
+fnmain(){
+phrases::greetings::hello();
+}
+
+// 03. phrases/src/lib.rs
+pubmodgreetings;// βοΈ Import `greetings` module as a public module
+
02. Dependency crate on Cargo.toml
When the code in the lib.rs file is getting larger, we can move those into a separate library crate and use it as a dependency of the main crate. As we mentioned earlier, a dependency can be specified from a folder path, git repository or by crates.io.
a. Using folder path
Letβs see how to create a nested crate and use it as a dependency using folder path,
If you want to use a library crate on multiple projects, one way is moving crate code to a git repository and use it as a dependency when needed.
// -- Cargo.toml --
+[dependencies]
+
+// 01. Get the latest commit on the master branch
+rocket={git="https://github.com/SergioBenitez/Rocket"}
+
+// 02. Get the latest commit of a specific branch
+rocket={git="https://github.com/SergioBenitez/Rocket",branch="v0.3"}
+
+// 03. Get a specific tag
+rocket={git="https://github.com/SergioBenitez/Rocket",tag="v0.3.2"}
+
+// 04. Get a specific revision (on master or any branch, according to rev)
+rocket={git="https://github.com/SergioBenitez/Rocket",rev="8183f636305cef4adaa9525506c33cbea72d1745"}
+
c. Using crates.io
The other way is uploading it to crates.io and use it as a dependency when needed.
π§ First, letβs create a simple βHello worldβ crate and upload it to crates.io.
// # Think we run,
+cargonewtest_crate_hello_world--lib
+
+// # It generates,
+test_crate_hello_world
+βββCargo.toml
+βββsrc
+βββlib.rs
+
+// # Think we modify following files,
+
+// 01. test_crate_hello_world/Cargo.toml
+[package]
+name="test_crate_hello_world"
+version="0.1.0"
+authors=["Dumindu Madunuwan"]
+
+description="A Simple Hello World Crate"
+repository="https://github.com/dumindu/test_crate_hello_world"
+keywords=["hello","world"]
+license="Apache-2.0"
+
+[dependencies]
+
+// 02. test_crate_hello_world/src/lib.rs
+//! A Simple Hello World Crate
+
+/// This function returns the greeting; `Hello, world!`
+pubfnhello()-> String{
+("Hello, world!").to_string()
+}
+
+#[cfg(test)]
+modtests{
+
+usesuper::hello;
+
+#[test]
+fntest_hello(){
+assert_eq!(hello(),"Hello, world!");
+}
+}
+
π //! doc comments are used to write crate and module-level documentation. On other places, we have to use /// outside of the block. And when uploading a crate to crates.io, cargo generates the documentation from these doc comments and host it on docs.rs.
π‘ We have to add the description and license fields to Cargo.toml. Otherwise, we will get error: api errors: missing or empty metadata fields: description, license. Please see http://doc.crates.io/manifest.html
To upload this to crates.io,
We have to create an account on crates.io to acquire an API token
Then run cargo login <token> with that API token and cargo publish
Youβll need an account on crates.io to acquire an API token. To do so, visit the home page and log in via a GitHub account (required for now). After this, visit your Account Settings page and run the cargo login command specified.
+Ex. cargo login abcdefghijklmnopqrstuvwxyz012345
The next step is to package up your crate into a format that can be uploaded to crates.io. For this weβll use the cargo package sub-command.
Now, it can be uploaded to crates.io with the cargo publish command.
If youβd like to skip the cargo package step, the cargo publish sub-command will automatically package up the local crate if a copy isnβt found already.
By default, Cargo looks dependencies on crates.io. So we have to add only the crate name and a version string to Cargo.toml and then run cargo build to fetch the dependencies and compile them.
\ No newline at end of file
diff --git a/docs/docs/custom-error-types/index.html b/docs/docs/custom-error-types/index.html
new file mode 100644
index 0000000..48ec9ff
--- /dev/null
+++ b/docs/docs/custom-error-types/index.html
@@ -0,0 +1,228 @@
+Custom Error Types Β· Learning Rust
+
Rust allow us to create our own Err types. We call them βCustom Error Typesβ.
Error trait
As you know traits define the functionality a type must provide. But we donβt always need to define new traits for common functionalities, because Rust standard library provides reusable traits which can be implemented on our own types. While creating custom error types the std::error::Error trait helps us to convert any type to an Err type.
As we discussed under traits inheritance, a trait can be inherited from another traits. trait Error: Debug + Display means Error trait inherits from fmt::Debug and fmt::Display traits.
How should the end user see this error as a message/ user-facing output.
Usually print via println!("{}") or eprintln!("{}")
Debug
How should display the Err while debugging/ programmer-facing output.
Usually print via println!("{:?}") or eprintln!("{:?}")
To pretty-print, println!("{:#?}") or eprintln!("{:#?}") can be used.
source()
The lower-level source of this error, if any.
Optional.
First, letβs see how to implement std::error::Error trait on a simplest custom error type.
usestd::fmt;
+
+// Custom error type; can be any type which defined in the current crate
+// π‘ In here, we use a simple "unit struct" to simplify the example
+structAppError;
+
+// Implement std::fmt::Display for AppError
+implfmt::DisplayforAppError{
+fnfmt(&self,f: &mutfmt::Formatter)-> fmt::Result{
+write!(f,"An Error Occurred, Please Try Again!")// user-facing output
+}
+}
+
+// Implement std::fmt::Debug for AppError
+implfmt::DebugforAppError{
+fnfmt(&self,f: &mutfmt::Formatter)-> fmt::Result{
+write!(f,"{{ file: {}, line: {} }}",file!(),line!())// programmer-facing output
+}
+}
+
+// A sample function to produce an AppError Err
+fnproduce_error()-> Result<(),AppError>{
+Err(AppError)
+}
+
+fnmain(){
+matchproduce_error(){
+Err(e)=>eprintln!("{}",e),// An Error Occurred, Please Try Again!
+_=>println!("No error"),
+}
+
+eprintln!("{:?}",produce_error());// Err({ file: src/main.rs, line: 17 })
+}
+
Hope you understood the main points. Now, letβs see a custom error type with an error code and an error message.
usestd::fmt;
+
+structAppError{
+code: usize,
+message: String,
+}
+
+// Different error messages according to AppError.code
+implfmt::DisplayforAppError{
+fnfmt(&self,f: &mutfmt::Formatter)-> fmt::Result{
+leterr_msg=matchself.code{
+404=>"Sorry, Can not find the Page!",
+_=>"Sorry, something is wrong! Please Try Again!",
+};
+
+write!(f,"{}",err_msg)
+}
+}
+
+// A unique format for dubugging output
+implfmt::DebugforAppError{
+fnfmt(&self,f: &mutfmt::Formatter)-> fmt::Result{
+write!(
+f,
+"AppError {{ code: {}, message: {} }}",
+self.code,self.message
+)
+}
+}
+
+fnproduce_error()-> Result<(),AppError>{
+Err(AppError{
+code: 404,
+message: String::from("Page not found"),
+})
+}
+
+fnmain(){
+matchproduce_error(){
+Err(e)=>eprintln!("{}",e),// Sorry, Can not find the Page!
+_=>println!("No error"),
+}
+
+eprintln!("{:?}",produce_error());// Err(AppError { code: 404, message: Page not found })
+
+eprintln!("{:#?}",produce_error());
+// Err(
+// AppError { code: 404, message: Page not found }
+// )
+}
+
βοΈ Rust standard library provides not only reusable traits and also it facilitates to magically generate implementations for few traits via #[derive] attribute. Rust support derivestd::fmt::Debug, to provide a default format for debug messages. So we can skip std::fmt::Debug implementation for custom error types and use #[derive(Debug)] before struct declaration.
For a struct #[derive(Debug)] prints, the name of the struct , { , comma-separated list of each fieldβs name and debug value and }.
usestd::fmt;
+
+#[derive(Debug)]// derive std::fmt::Debug on AppError
+structAppError{
+code: usize,
+message: String,
+}
+
+implfmt::DisplayforAppError{
+fnfmt(&self,f: &mutfmt::Formatter)-> fmt::Result{
+leterr_msg=matchself.code{
+404=>"Sorry, Can not find the Page!",
+_=>"Sorry, something is wrong! Please Try Again!",
+};
+
+write!(f,"{}",err_msg)
+}
+}
+
+fnproduce_error()-> Result<(),AppError>{
+Err(AppError{
+code: 404,
+message: String::from("Page not found"),
+})
+}
+
+fnmain(){
+matchproduce_error(){
+Err(e)=>eprintln!("{}",e),// Sorry, Can not find the Page!
+_=>println!("No error"),
+}
+
+eprintln!("{:?}",produce_error());// Err(AppError { code: 404, message: Page not found })
+
+eprintln!("{:#?}",produce_error());
+// Err(
+// AppError {
+// code: 404,
+// message: "Page not found"
+// }
+// )
+}
+
From trait
When writing real programs, we mostly have to deal with different modules, different std and third party crates at the same time. Each crate uses their own error types. However, if we are using our own error type, we should convert those errors into our error type. For these conversions, we can use the standardized trait std::convert::From.
π‘ As you know, String::from() function is used to create a String from &str data type. Actually this also an implementation of std::convert::From trait.
Letβs see how to implement std::convert::From trait on a custom error type.
usestd::fs::File;
+usestd::io;
+
+#[derive(Debug)]
+structAppError{
+kind: String,// type of the error
+message: String,// error message
+}
+
+// Implement std::convert::From for AppError; from io::Error
+implFrom<io::Error>forAppError{
+fnfrom(error: io::Error)-> Self{
+AppError{
+kind: String::from("io"),
+message: error.to_string(),
+}
+}
+}
+
+fnmain()-> Result<(),AppError>{
+let_file=File::open("nonexistent_file.txt")?;// This generates an io::Error. But because of return type is Result<(), AppError>, it converts to AppError
+
+Ok(())
+}
+
+
+// --------------- Run time error ---------------
+Error: AppError{kind: "io",message: "No such file or directory (os error 2)"}
+
In the above example, File::open(βnonexistent.txtβ)? produces std::io::Error. But because of the return type is Result<(), AppError>, it converts to an AppError. Because of we are propagating the error from main() function, it prints the Debug representation of the Err.
In the above example we deal with only one std error type, std::io::Error. Letβs see some example which handles multiple std error types.
usestd::fs::File;
+usestd::io::{self,Read};
+usestd::num;
+
+#[derive(Debug)]
+structAppError{
+kind: String,
+message: String,
+}
+
+// Implement std::convert::From for AppError; from io::Error
+implFrom<io::Error>forAppError{
+fnfrom(error: io::Error)-> Self{
+AppError{
+kind: String::from("io"),
+message: error.to_string(),
+}
+}
+}
+
+// Implement std::convert::From for AppError; from num::ParseIntError
+implFrom<num::ParseIntError>forAppError{
+fnfrom(error: num::ParseIntError)-> Self{
+AppError{
+kind: String::from("parse"),
+message: error.to_string(),
+}
+}
+}
+
+fnmain()-> Result<(),AppError>{
+letmutfile=File::open("hello_world.txt")?;// generates an io::Error, if can not open the file and converts to an AppError
+
+letmutcontent=String::new();
+file.read_to_string(&mutcontent)?;// generates an io::Error, if can not read file content and converts to an AppError
+
+let_number: usize;
+_number=content.parse()?;// generates num::ParseIntError, if can not convert file content to usize and converts to an AppError
+
+Ok(())
+}
+
+
+// --------------- Few possible run time errors ---------------
+
+// 01. If hello_world.txt is a nonexistent file
+Error: AppError{kind: "io",message: "No such file or directory (os error 2)"}
+
+// 02. If user doesn't have relevant permission to access hello_world.txt
+Error: AppError{kind: "io",message: "Permission denied (os error 13)"}
+
+// 03. If hello_world.txt contains non-numeric content. ex Hello, world!
+Error: AppError{kind: "parse",message: "invalid digit found in string"}
+
π Search about the implementation of std::io::ErrorKind, to see how to organize error types further.
\ No newline at end of file
diff --git a/docs/docs/enums/index.html b/docs/docs/enums/index.html
new file mode 100644
index 0000000..d689af8
--- /dev/null
+++ b/docs/docs/enums/index.html
@@ -0,0 +1,45 @@
+Enums Β· Learning Rust
+
βοΈ An enum is a single type. It contains variants, which are possible values of the enum at a given time. For example,
enumDay{
+Sunday,
+Monday,
+Tuesday,
+Wednesday,
+Thursday,
+Friday,
+Saturday
+}
+
+// The `Day` is the enum
+// Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday are the variants
+
βοΈ Variants can be accessed throughΒ :: notation, ex. Day::Sunday
βοΈ Each enum variant can have,
No data (unit variant)
Unnamed ordered data (tuple variant)
Named data (struct variant)
enumFlashMessage{
+Success,// A unit variant
+Warning{category: i32,message: String},// A struct variant
+Error(String)// A tuple variant
+}
+
+fnmain(){
+letmutform_status=FlashMessage::Success;
+print_flash_message(form_status);
+
+form_status=FlashMessage::Warning{category: 2,message: String::from("Field X is required")};
+print_flash_message(form_status);
+
+form_status=FlashMessage::Error(String::from("Connection Error"));
+print_flash_message(form_status);
+}
+
+fnprint_flash_message(m: FlashMessage){
+// Pattern matching with enum
+matchm{
+FlashMessage::Success=>
+println!("Form Submitted correctly"),
+FlashMessage::Warning{category,message}=>// Destructure, should use same field names
+println!("Warning : {} - {}",category,message),
+FlashMessage::Error(msg)=>
+println!("Error : {}",msg)
+}
+}
+
\ No newline at end of file
diff --git a/docs/docs/error-and-none-propagation/index.html b/docs/docs/error-and-none-propagation/index.html
new file mode 100644
index 0000000..1e3151e
--- /dev/null
+++ b/docs/docs/error-and-none-propagation/index.html
@@ -0,0 +1,73 @@
+Error and None Propagation Β· Learning Rust
+
We should use panics like panic!(), unwrap(), expect() only if we can not handle the situation in a better way. Also if a function contains expressions which can produce either None or Err,
we can handle them inside the same function. Or,
we can return None and Err types immediately to the caller. So the caller can decide how to handle them.
π‘ None types no need to handle by the caller of the function always. But Rustsβ convention to handle Err types is, return them immediately to the caller to give more control to the caller to decide how to handle them.
? Operator
If an Option type has Some value or a Result type has a Ok value, the value inside them passes to the next step.
If the Option type has None value or the Result type has Err value, return them immediately to the caller of the function.
Example with Option type,
fnmain(){
+ifcomplex_function().is_none(){
+println!("X not exists!");
+}
+}
+
+fncomplex_function()-> Option<&'staticstr>{
+letx=get_an_optional_value()?;// if None, returns immediately; if Some("abc"), set x to "abc"
+
+// some other code, ex
+println!("{}",x);// "abc" ; if you change line 19 `false` to `true`
+
+Some("")
+}
+
+fnget_an_optional_value()-> Option<&'staticstr>{
+
+//if the optional value is not empty
+iffalse{
+returnSome("abc");
+}
+
+//else
+None
+}
+
Example with Result Type,
fnmain(){
+// `main` function is the caller of `complex_function` function
+// So we handle errors of complex_function(), inside main()
+ifcomplex_function().is_err(){
+println!("Can not calculate X!");
+}
+}
+
+fncomplex_function()-> Result<u64,String>{
+letx=function_with_error()?;// if Err, returns immediately; if Ok(255), set x to 255
+
+// some other code, ex
+println!("{}",x);// 255 ; if you change line 20 `true` to `false`
+
+Ok(0)
+}
+
+fnfunction_with_error()-> Result<u64,String>{
+//if error happens
+iftrue{
+returnErr("some message".to_string());
+}
+
+// else, return valid output
+Ok(255)
+}
+
try!()
β ? operator was added in Rust version 1.13. try!() macro is the old way to propagate errors before that. So we should avoid using this now.
If a Result type has Ok value, the value inside it passes to the next step. If it has Err value, returns it immediately to the caller of the function.
// using `?`
+letx=function_with_error()?;// if Err, returns immediately; if Ok(255), set x to 255
+
+// using `try!()`
+letx=try!(function_with_error());
+
Error propagation fromΒ main()
Before Rust version 1.26, we couldn’t propagate Result and Option types from the main() function. But now, we can propagate Result types from the main() function and it prints the Debug representation of the Err.
π‘ We are going to discuss about Debug representations under Error trait section.
usestd::fs::File;
+
+fnmain()-> std::io::Result<()>{
+let_=File::open("not-existing-file.txt")?;
+
+Ok(())// Because of the default return value of Rust functions is an empty tuple/ ()
+}
+
+// Because of the program can not find not-existing-file.txt , it produces,
+// Err(Os { code: 2, kind: NotFound, message: "No such file or directory" })
+// While propagating error, the program prints,
+// Error: Os { code: 2, kind: NotFound, message: "No such file or directory" }
+
Functions are the first line of organization in any program.
fnmain(){
+greet();// Do one thing
+ask_location();// Do another thing
+}
+
+fngreet(){
+println!("Hello!");
+}
+
+fnask_location(){
+println!("Where are you from?");
+}
+
We can add unit tests in the same file.
fnmain(){
+greet();
+}
+
+fngreet()-> String{
+"Hello, world!".to_string()
+}
+
+#[test]// Test attribute indicates this is a test function
+fntest_greet(){
+assert_eq!("Hello, world!",greet())
+}
+
+// π‘ Always put test functions inside a tests module with #[cfg(test)] attribute.
+// cfg(test) module compiles only when running tests. We discuss more about this in the next section.
+
π An attribute is a general, free-form metadatum that is interpreted according to name, convention, and language and compiler version.
\ No newline at end of file
diff --git a/docs/docs/functions/index.html b/docs/docs/functions/index.html
new file mode 100644
index 0000000..8a47713
--- /dev/null
+++ b/docs/docs/functions/index.html
@@ -0,0 +1,66 @@
+Functions Β· Learning Rust
+
When using arguments, you must declare the data types.
By default, functions return an empty tuple/ (). If you want to return a value, the return type must be specified after ->
i. Hello world
fnmain(){
+println!("Hello, world!");
+}
+
ii. Passing arguments
fnprint_sum(a: i8,b: i8){
+println!("sum is: {}",a+b);
+}
+
iii. Returning values
// 01. Without the return keyword. Only the last expression returns.
+fnplus_one(a: i32)-> i32{
+a+1
+// There is no ending ; in the above line.
+// It means this is an expression which equals to `return a + 1;`.
+}
+
// 02. With the return keyword.
+fnplus_two(a: i32)-> i32{
+returna+2;
+// Should use return keyword only on conditional/ early returns.
+// Using return keyword in the last expression is a bad practice.
+}
+
iv. Function pointers, Usage as a Data Type
fnmain(){
+// 01. Without type declarations.
+letp1=plus_one;
+letx=p1(5);// 6
+
+// 02. With type declarations.
+letp1: fn(i32)-> i32=plus_one;
+letx=p1(5);// 6
+}
+
+fnplus_one(a: i32)-> i32{
+a+1
+}
+
Closures
Also known as anonymous functions or lambda functions.
The data types of arguments and returns are optional β°β±α΅.
Example with a named function, before using closures.
i. With optional type declarations of input and return types
fnmain(){
+letx=2;
+letsquare=|i: i32|-> i32{// Input parameters are passed inside | | and expression body is wrapped within { }
+i*i
+};
+println!("{}",square(x));
+}
+
ii. Without type declarations of input and return types
fnmain(){
+letx=2;
+letsquare=|i|i*i;// { } are optional for single-lined closures
+println!("{}",square(x));
+}
+
iii. With optional type declarations; Creating and calling together
fnmain(){
+letx=2;
+letx_square=|i: i32|-> i32{i*i}(x);// { } are mandatory while creating and calling same time.
+println!("{}",x_square);
+}
+
iv. Without optional type declarations; Creating and calling together
fnmain(){
+letx=2;
+letx_square=|i|-> i32{i*i}(x);// βοΈ The return type is mandatory.
+println!("{}",x_square);
+}
+
\ No newline at end of file
diff --git a/docs/docs/generics/index.html b/docs/docs/generics/index.html
new file mode 100644
index 0000000..7ec8973
--- /dev/null
+++ b/docs/docs/generics/index.html
@@ -0,0 +1,91 @@
+Generics Β· Learning Rust
+
π Sometimes, when writing a function or data type, we may want it to work for multiple types of arguments. In Rust, we can do this with generics.
π The concept is, instead of declaring a specific data type we use an uppercase letter(or PascalCase identifier). ex, instead of xΒ : u8 we use xΒ : TΒ . but we have to inform to the compiler that T is a generic type(can be any type) by adding <T> at first.
Generalizing functions
fntakes_anything<T>(x: T){// x has type T, T is a generic type
+}
+
+fntakes_two_of_the_same_things<T>(x: T,y: T){// Both x and y has the same type
+}
+
+fntakes_two_things<T,U>(x: T,y: U){// Multiple types
+}
+
Generalizing structs
structPoint<T>{
+x: T,
+y: T,
+}
+
+fnmain(){
+letpoint_a=Point{x: 0,y: 0};// T is a int type
+letpoint_b=Point{x: 0.0,y: 0.0};// T is a float type
+}
+
+// π When adding an implementation for a generic struct, the type parameters should be declared after the impl as well
+// impl<T> Point<T> {
+
βοΈ Above Option and Result types are kind of special generic types which are already defined in Rustβs standard library.Β
An optional value can have either Some value or no value/ None.
A result can represent either success/ Ok or failure/ Err
Usages of Option
// 01 - - - - - - - - - - - - - - - - - - - - - -
+fnget_id_by_username(username: &str)-> Option<usize>{
+// if username can be found in the system, set userId
+returnSome(userId);
+// else
+None
+}
+
+// π So, on the above function, instead of setting return type as usize
+// set return type as Option<usize>
+// Instead of return userId, return Some(userId)
+// else None (π‘remember? last return statement no need return keyword and ending ;)
+
+// 02 - - - - - - - - - - - - - - - - - - - - - -
+structTask{
+title: String,
+assignee: Option<Person>,
+}
+
+// π Instead of assignee: Person, we use Option<Person>
+// because the task has not been assigned to a specific person
+
+// - - - - - - - - - - - - - - - - - - - - - - -
+// When using Option types as return types on functions
+// we can use pattern matching to catch the relevant return type(Some/None) when calling them
+
+fnmain(){
+letusername="anonymous";
+matchget_id_by_username(username){
+None=>println!("User not found"),
+Some(i)=>println!("User Id: {}",i)
+}
+}
+
Usages of Result
π The Option type is a way to use Rustβs type system to express the possibility of absence. Result expresses the possibility of error.
// - - - - - - - - - - - - - - - - - - - - - -
+fnget_word_count_from_file(file_name: &str)-> Result<u32,&str>{
+// if the file is not found on the system, return error
+returnErr("File can not be found!")
+// else, count and return the word count
+// let mut word_count: u32; ....
+Ok(word_count)
+}
+
+// π On the above function,
+// instead panic(break) the app, when the file can not be found; return Err(something)
+// or when it could get the relevant data; return Ok(data)
+
+
+// - - - - - - - - - - - - - - - - - - - - - - -
+// We can use pattern matching to catch the relevant return type(Ok/Err) when calling it
+
+fnmain(){
+letmutfile_name="file_a";
+matchget_word_count_from_file(file_name){
+Ok(i)=>println!("Word Count: {}",i),
+Err(e)=>println!("Error: {}",e)
+}
+}
+
π Many useful methods have been implemented around Option and Result types. More information can be found on std::option::Option and std::result::Result pages on Rust doc.
βοΈ Also more practical examples of options & results can be found on Error Handling section in Rust doc.
\ No newline at end of file
diff --git a/docs/docs/hello-world/index.html b/docs/docs/hello-world/index.html
new file mode 100644
index 0000000..e80ac66
--- /dev/null
+++ b/docs/docs/hello-world/index.html
@@ -0,0 +1,36 @@
+Hello World Β· Learning Rust
+
fn means function. The main function is the beginning of every Rust program. println!() prints text to the console and its ! indicates that itβs a macro rather than a function.
π‘ Rust files should have .rs file extension and if youβre using more than one word for the file name, follow the snake_case convention.
Save the above code in file.rs , but it can be any name with .rs extension.
Compile it with rustc file.rs
Execute it with ./file on Linux and Mac or file.exe on Windows
These are the other usages of the println!() macro,
fnmain(){
+println!("{}, {}!","Hello","world");// Hello, world!
+println!("{0}, {1}!","Hello","world");// Hello, world!
+println!("{greeting}, {name}!",greeting="Hello",name="world");// Hello, world!
+
+let(greeting,name)=("Hello","world");// π‘ Two Variable bindings declare & initialize in one line.
+println!("{greeting}, {name}!");// Hello, world!
+
+println!("{:?}",[1,2,3]);// [1, 2, 3]
+println!("{:#?}",[1,2,3]);
+/*
+ [
+ 1,
+ 2,
+ 3
+ ]
+ */
+
+// π The format! macro is used to store the formatted string.
+letx=format!("{}, {}!","Hello","world");
+println!("{}",x);// Hello, world!
+
+// π‘ Rust has a print!() macro as well
+print!("Hello, world!");// Without new line
+println!();// A new line
+
+print!("Hello, world!\n");// With new line
+}
+
π‘ When we discussed about C-like structs, I mentioned that those are similar to classes in OOP languages but without their methods. impls are used to define methods for Rust structs and enums.
π‘ Traits are kind of similar to interfaces in OOP languages. They are used to define the functionality a type must provide. Multiple traits can be implemented for a single type.
βοΈοΈ But traits can also include default implementations of methods. Default methods can be overridden when implementing types.
Impls without traits
structPlayer{
+first_name: String,
+last_name: String,
+}
+
+implPlayer{
+fnfull_name(&self)-> String{
+format!("{}{}",self.first_name,self.last_name)
+}
+}
+
+fnmain(){
+letplayer_1=Player{
+first_name: "Rafael".to_string(),
+last_name: "Nadal".to_string(),
+};
+
+println!("Player 01: {}",player_1.full_name());
+}
+
+// βοΈ Implementation must appear in the same crate as the self type
+
Impls & traits, without default methods
structPlayer{
+first_name: String,
+last_name: String,
+}
+
+traitFullName{
+fnfull_name(&self)-> String;
+}
+
+implFullNameforPlayer{
+fnfull_name(&self)-> String{
+format!("{}{}",self.first_name,self.last_name)
+}
+}
+
+fnmain(){
+letplayer_2=Player{
+first_name: "Roger".to_string(),
+last_name: "Federer".to_string(),
+};
+
+println!("Player 02: {}",player_2.full_name());
+}
+
+// π Other than functions, traits can contain constants and types.
+
+// π‘ And also in Rust, new traits can be implemented for existing types even for types like i8, f64 and etc.
+// Same way existing traits can be implemented for new types you are creating.
+
Impls, traits & default methods
traitFoo{
+fnbar(&self);
+fnbaz(&self){println!("We called baz.");}
+}
+
βοΈ As you can see methods take a special first parameter, the type itself. It can be either self, &self, or &mut self; self if itβs a value on the stack (taking ownership), &self if itβs a reference, and &mut self if itβs a mutable reference.
Impls with Associated functions
Some other languages support static methods. At such times, we call a function directly through the class without creating an object. In Rust, we call them Associated Functions. we useΒ :: instead ofΒ . when calling them from the struct.
+ex. Person::new(βElon Musk Jrβ);
structPlayer{
+first_name: String,
+last_name: String,
+}
+
+implPlayer{
+fnnew(first_name: String,last_name: String)-> Player{
+Player{
+first_name: first_name,
+last_name: last_name,
+}
+}
+
+fnfull_name(&self)-> String{
+format!("{}{}",self.first_name,self.last_name)
+}
+}
+
+fnmain(){
+letplayer_name=Player::new("Serena".to_string(),"Williams".to_string()).full_name();
+println!("Player: {}",player_name);
+}
+
+// We have used :: notation for `new()` and . notation for `full_name()`
+
+// π Also in here, instead of using new() and full_name() separately as two expressions,
+// we can use Method Chaining. ex. `player.add_points(2).get_point_count();`
+
Traits with generics
traitFrom<T>{
+fnfrom(T)-> Self;
+}
+
+implFrom<u8>foru16{
+//...
+}
+implFrom<u8>foru32{
+//...
+}
+// Should specify after the trait name like generic functions
+
Traits inheritance
traitPerson{
+fnfull_name(&self)-> String;
+}
+
+traitEmployee: Person{// Employee inherits from person trait
+fnjob_title(&self)-> String;
+}
+
+traitExpatEmployee: Employee+Expat{// ExpatEmployee inherits from Employee and Expat traits
+fnadditional_tax(&self)-> f64;
+}
+
Trait objects
π While Rust favors static dispatch, it also supports dynamic dispatch through a mechanism called βtrait objects.β
π Dynamic dispatch is the process of selecting which implementation of a polymorphic operation (method or function) to call at run time.
\ No newline at end of file
diff --git a/docs/docs/index.html b/docs/docs/index.html
new file mode 100644
index 0000000..cd3b06b
--- /dev/null
+++ b/docs/docs/index.html
@@ -0,0 +1,2 @@
+https://learning-rust.github.io/docs/overview/
+
\ No newline at end of file
diff --git a/docs/docs/index.xml b/docs/docs/index.xml
new file mode 100644
index 0000000..08d4674
--- /dev/null
+++ b/docs/docs/index.xml
@@ -0,0 +1,503 @@
+Docs on Learning Rusthttps://learning-rust.github.io/docs/Recent content in Docs on Learning RustHugoen-USBorrowinghttps://learning-rust.github.io/docs/borrowing/Mon, 01 Jan 0001 00:00:00 +0000https://learning-rust.github.io/docs/borrowing/<p>In real life applications, most of the times we have to pass variable bindings to other functions or assign them to other variable bindings. In this case, we are <strong>referencing</strong> the original binding; <strong>borrow</strong> the data of it.</p>
+<h2 id="what-is-borrowing">What is Borrowing?</h2>
+<blockquote>
+<p><a href="https://github.com/nikomatsakis/rust-tutorials-keynote/blob/master/Ownership%20and%20Borrowing.pdf" target="_blank" >Borrow (verb)</a><br>
+To receive something with the promise of returning it.</p></blockquote>
+<h2 id="shared--mutable-borrowings">Shared & Mutable borrowings</h2>
+<p>βοΈ There are two types of Borrowing,</p>
+<ol>
+<li>
+<p><strong>Shared Borrowing</strong> <code>(&T)</code></p>
+<ul>
+<li>A piece of data can be <strong>borrowed by a single or multiple users</strong>, but <strong>data should not be altered</strong>.</li>
+</ul>
+</li>
+<li>
+<p><strong>Mutable Borrowing</strong> <code>(&mut T)</code></p>Cargo, Crates and Basic Project Structurehttps://learning-rust.github.io/docs/cargo-crates-and-basic-project-structure/Mon, 01 Jan 0001 00:00:00 +0000https://learning-rust.github.io/docs/cargo-crates-and-basic-project-structure/<h2 id="cargo">Cargo</h2>
+<p>Cargo is Rustβs built-in package manager and build system. It also supports the following actions,</p>
+<table>
+ <thead>
+ <tr>
+ <th>Command</th>
+ <th>Action</th>
+ </tr>
+ </thead>
+ <tbody>
+ <tr>
+ <td><code>cargo new</code></td>
+ <td>Create a new project</td>
+ </tr>
+ <tr>
+ <td><code>cargo init</code></td>
+ <td>Create a new project in an existing directory</td>
+ </tr>
+ <tr>
+ <td><code>cargo check</code></td>
+ <td>Verify the project compiles without errors</td>
+ </tr>
+ <tr>
+ <td><code>cargo build</code></td>
+ <td>Build the executable</td>
+ </tr>
+ <tr>
+ <td><code>cargo run</code></td>
+ <td>Build the executable and run</td>
+ </tr>
+ </tbody>
+</table>
+<blockquote>
+<p>π‘ The <code>cargo check</code> command verifies that the project compiles without errors, without producing an executable.
+Thus, it is often faster than <code>cargo build</code>.</p>Code Organizationhttps://learning-rust.github.io/docs/code-organization/Mon, 01 Jan 0001 00:00:00 +0000https://learning-rust.github.io/docs/code-organization/<p>When a single code block is getting larger, it should be decomposed into smaller pieces and should be organized in a proper manner. Rust supports different levels of code organization.</p>
+<h2 id="1-functions">1. Functions</h2>
+<h2 id="2-modules">2. Modules</h2>
+<p>Can be mapped to a,</p>
+<ul>
+<li><strong>Inline module</strong></li>
+<li><strong>File</strong></li>
+<li><strong>Directory hierarchy</strong></li>
+</ul>
+<h2 id="3-crates">3. Crates</h2>
+<p>Can be mapped to a,</p>
+<ul>
+<li>
+<p><strong>lib.rs file on the same executable crate</strong></p>
+</li>
+<li>
+<p><strong>Dependency crate specified on Cargo.toml</strong></p>
+<p>Can be specified from,</p>
+<ul>
+<li><strong>Path</strong></li>
+<li><strong>Git repository</strong></li>
+<li><strong>crates.io</strong></li>
+</ul>
+</li>
+</ul>
+<h2 id="4-workspaces">4. Workspaces</h2>
+<p>Helps to manage multiple crates as a single project.</p>Combinatorshttps://learning-rust.github.io/docs/combinators/Mon, 01 Jan 0001 00:00:00 +0000https://learning-rust.github.io/docs/combinators/<h2 id="what-is-a-combinator">What is a combinator?</h2>
+<ul>
+<li>
+<p>One meaning of βcombinatorβ is a more informal sense referring to the <strong>combinator pattern</strong>, a style of organizing libraries centered around the idea of combining things. Usually there is <strong>some type T</strong>, some <strong>functions for constructing βprimitiveβ values of type T</strong>, and some β<strong>combinators</strong>β which can <strong>combine values of type T</strong> in various ways to <strong>build up more complex values of type T</strong>. The other definition is <strong>“function with no free variables”</strong>.
+__ <a href="https://wiki.haskell.org/Combinator" target="_blank" >wiki.haskell.org</a></p>Comments and Documenting the codehttps://learning-rust.github.io/docs/comments-and-documenting-the-code/Mon, 01 Jan 0001 00:00:00 +0000https://learning-rust.github.io/docs/comments-and-documenting-the-code/<h2 id="comments">Comments</h2>
+<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-rust" data-lang="rust"><span class="line"><span class="cl"><span class="c1">// Line comments
+</span></span></span><span class="line"><span class="cl"><span class="c1"></span><span class="cm">/* Block comments */</span><span class="w">
+</span></span></span></code></pre></div><p>Nested block comments are supported.</p>
+<p>π‘ <strong>By convention, try to avoid using block comments. Use line comments instead.</strong></p>
+<h2 id="doc-comments">Doc Comments</h2>
+<p><a href="https://learning-rust.github.io/docs/cargo-crates-and-basic-project-structure/#cargo" >As we discussed</a>, we can generate the project documentation via <a href="https://doc.rust-lang.org/stable/rustdoc/" target="_blank" >rustdoc</a> by running the <strong><code>cargo doc</code></strong> command. It uses the doc comments to generate the documentation.</p>
+<p>π‘ Usually we are adding doc comments on library crates. Also, we can use <a href="https://github.com/adam-p/markdown-here/wiki/Markdown-Cheatsheet" target="_blank" >Markdown notations</a> inside the doc comments.</p>Control Flowshttps://learning-rust.github.io/docs/control-flows/Mon, 01 Jan 0001 00:00:00 +0000https://learning-rust.github.io/docs/control-flows/<h2 id="if---else-if---else">if - else if - else</h2>
+<ul>
+<li>Using only <code>if</code> block.</li>
+</ul>
+<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-rust" data-lang="rust"><span class="line"><span class="cl"><span class="kd">let</span><span class="w"> </span><span class="n">age</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="mi">13</span><span class="p">;</span><span class="w">
+</span></span></span><span class="line"><span class="cl"><span class="w">
+</span></span></span><span class="line"><span class="cl"><span class="w"></span><span class="k">if</span><span class="w"> </span><span class="n">age</span><span class="w"> </span><span class="o"><</span><span class="w"> </span><span class="mi">18</span><span class="w"> </span><span class="p">{</span><span class="w">
+</span></span></span><span class="line"><span class="cl"><span class="w"> </span><span class="fm">println!</span><span class="p">(</span><span class="s">"Hello, child!"</span><span class="p">);</span><span class="w"> </span><span class="c1">// The code prints this
+</span></span></span><span class="line"><span class="cl"><span class="c1"></span><span class="p">}</span><span class="w">
+</span></span></span></code></pre></div><ul>
+<li>Using only <code>if</code> and <code>else</code> blocks.</li>
+</ul>
+<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-rust" data-lang="rust"><span class="line"><span class="cl"><span class="kd">let</span><span class="w"> </span><span class="n">i</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="mi">7</span><span class="p">;</span><span class="w">
+</span></span></span><span class="line"><span class="cl"><span class="w">
+</span></span></span><span class="line"><span class="cl"><span class="w"></span><span class="k">if</span><span class="w"> </span><span class="n">i</span><span class="w"> </span><span class="o">%</span><span class="w"> </span><span class="mi">2</span><span class="w"> </span><span class="o">==</span><span class="w"> </span><span class="mi">0</span><span class="w"> </span><span class="p">{</span><span class="w">
+</span></span></span><span class="line"><span class="cl"><span class="w"> </span><span class="fm">println!</span><span class="p">(</span><span class="s">"Even"</span><span class="p">);</span><span class="w">
+</span></span></span><span class="line"><span class="cl"><span class="w"></span><span class="p">}</span><span class="w"> </span><span class="k">else</span><span class="w"> </span><span class="p">{</span><span class="w">
+</span></span></span><span class="line"><span class="cl"><span class="w"> </span><span class="fm">println!</span><span class="p">(</span><span class="s">"Odd"</span><span class="p">);</span><span class="w"> </span><span class="c1">// The code prints this
+</span></span></span><span class="line"><span class="cl"><span class="c1"></span><span class="p">}</span><span class="w">
+</span></span></span></code></pre></div><ul>
+<li>Using with <code>let</code> statement.</li>
+</ul>
+<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-rust" data-lang="rust"><span class="line"><span class="cl"><span class="kd">let</span><span class="w"> </span><span class="n">age</span>: <span class="kt">u8</span> <span class="o">=</span><span class="w"> </span><span class="mi">13</span><span class="p">;</span><span class="w">
+</span></span></span><span class="line"><span class="cl"><span class="w"></span><span class="kd">let</span><span class="w"> </span><span class="n">is_below_eighteen</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="k">if</span><span class="w"> </span><span class="n">age</span><span class="w"> </span><span class="o"><</span><span class="w"> </span><span class="mi">18</span><span class="w"> </span><span class="p">{</span><span class="w"> </span><span class="kc">true</span><span class="w"> </span><span class="p">}</span><span class="w"> </span><span class="k">else</span><span class="w"> </span><span class="p">{</span><span class="w"> </span><span class="kc">false</span><span class="w"> </span><span class="p">};</span><span class="w"> </span><span class="c1">// true
+</span></span></span></code></pre></div><ul>
+<li>More examples,</li>
+</ul>
+<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-rust" data-lang="rust"><span class="line"><span class="cl"><span class="c1">// i. A simple example
+</span></span></span><span class="line"><span class="cl"><span class="c1"></span><span class="kd">let</span><span class="w"> </span><span class="n">team_size</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="mi">7</span><span class="p">;</span><span class="w">
+</span></span></span><span class="line"><span class="cl"><span class="w">
+</span></span></span><span class="line"><span class="cl"><span class="w"></span><span class="k">if</span><span class="w"> </span><span class="n">team_size</span><span class="w"> </span><span class="o"><</span><span class="w"> </span><span class="mi">5</span><span class="w"> </span><span class="p">{</span><span class="w">
+</span></span></span><span class="line"><span class="cl"><span class="w"> </span><span class="fm">println!</span><span class="p">(</span><span class="s">"Small"</span><span class="p">);</span><span class="w">
+</span></span></span><span class="line"><span class="cl"><span class="w"></span><span class="p">}</span><span class="w"> </span><span class="k">else</span><span class="w"> </span><span class="k">if</span><span class="w"> </span><span class="n">team_size</span><span class="w"> </span><span class="o"><</span><span class="w"> </span><span class="mi">10</span><span class="w"> </span><span class="p">{</span><span class="w">
+</span></span></span><span class="line"><span class="cl"><span class="w"> </span><span class="fm">println!</span><span class="p">(</span><span class="s">"Medium"</span><span class="p">);</span><span class="w"> </span><span class="c1">// The code prints this
+</span></span></span><span class="line"><span class="cl"><span class="c1"></span><span class="p">}</span><span class="w"> </span><span class="k">else</span><span class="w"> </span><span class="p">{</span><span class="w">
+</span></span></span><span class="line"><span class="cl"><span class="w"> </span><span class="fm">println!</span><span class="p">(</span><span class="s">"Large"</span><span class="p">);</span><span class="w">
+</span></span></span><span class="line"><span class="cl"><span class="w"></span><span class="p">}</span><span class="w">
+</span></span></span></code></pre></div><div class="highlight"><pre tabindex="0" class="chroma"><code class="language-rust" data-lang="rust"><span class="line"><span class="cl"><span class="c1">// ii. Let's refactor above code
+</span></span></span><span class="line"><span class="cl"><span class="c1"></span><span class="kd">let</span><span class="w"> </span><span class="n">team_size</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="mi">7</span><span class="p">;</span><span class="w">
+</span></span></span><span class="line"><span class="cl"><span class="w"></span><span class="kd">let</span><span class="w"> </span><span class="n">team_size_in_text</span><span class="p">;</span><span class="w">
+</span></span></span><span class="line"><span class="cl"><span class="w">
+</span></span></span><span class="line"><span class="cl"><span class="w"></span><span class="k">if</span><span class="w"> </span><span class="n">team_size</span><span class="w"> </span><span class="o"><</span><span class="w"> </span><span class="mi">5</span><span class="w"> </span><span class="p">{</span><span class="w">
+</span></span></span><span class="line"><span class="cl"><span class="w"> </span><span class="n">team_size_in_text</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="s">"Small"</span><span class="p">;</span><span class="w">
+</span></span></span><span class="line"><span class="cl"><span class="w"></span><span class="p">}</span><span class="w"> </span><span class="k">else</span><span class="w"> </span><span class="k">if</span><span class="w"> </span><span class="n">team_size</span><span class="w"> </span><span class="o"><</span><span class="w"> </span><span class="mi">10</span><span class="w"> </span><span class="p">{</span><span class="w">
+</span></span></span><span class="line"><span class="cl"><span class="w"> </span><span class="n">team_size_in_text</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="s">"Medium"</span><span class="p">;</span><span class="w">
+</span></span></span><span class="line"><span class="cl"><span class="w"></span><span class="p">}</span><span class="w"> </span><span class="k">else</span><span class="w"> </span><span class="p">{</span><span class="w">
+</span></span></span><span class="line"><span class="cl"><span class="w"> </span><span class="n">team_size_in_text</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="s">"Large"</span><span class="p">;</span><span class="w">
+</span></span></span><span class="line"><span class="cl"><span class="w"></span><span class="p">}</span><span class="w">
+</span></span></span><span class="line"><span class="cl"><span class="w">
+</span></span></span><span class="line"><span class="cl"><span class="w"></span><span class="fm">println!</span><span class="p">(</span><span class="s">"Current team size : </span><span class="si">{}</span><span class="s">"</span><span class="p">,</span><span class="w"> </span><span class="n">team_size_in_text</span><span class="p">);</span><span class="w"> </span><span class="c1">// Current team size : Medium
+</span></span></span></code></pre></div><div class="highlight"><pre tabindex="0" class="chroma"><code class="language-rust" data-lang="rust"><span class="line"><span class="cl"><span class="c1">// iii. Let's refactor further
+</span></span></span><span class="line"><span class="cl"><span class="c1"></span><span class="kd">let</span><span class="w"> </span><span class="n">team_size</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="mi">7</span><span class="p">;</span><span class="w">
+</span></span></span><span class="line"><span class="cl"><span class="w"></span><span class="kd">let</span><span class="w"> </span><span class="n">team_size</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="k">if</span><span class="w"> </span><span class="n">team_size</span><span class="w"> </span><span class="o"><</span><span class="w"> </span><span class="mi">5</span><span class="w"> </span><span class="p">{</span><span class="w">
+</span></span></span><span class="line"><span class="cl"><span class="w"> </span><span class="s">"Small"</span><span class="w"> </span><span class="c1">// βοΈ no ;
+</span></span></span><span class="line"><span class="cl"><span class="c1"></span><span class="p">}</span><span class="w"> </span><span class="k">else</span><span class="w"> </span><span class="k">if</span><span class="w"> </span><span class="n">team_size</span><span class="w"> </span><span class="o"><</span><span class="w"> </span><span class="mi">10</span><span class="w"> </span><span class="p">{</span><span class="w">
+</span></span></span><span class="line"><span class="cl"><span class="w"> </span><span class="s">"Medium"</span><span class="w">
+</span></span></span><span class="line"><span class="cl"><span class="w"></span><span class="p">}</span><span class="w"> </span><span class="k">else</span><span class="w"> </span><span class="p">{</span><span class="w">
+</span></span></span><span class="line"><span class="cl"><span class="w"> </span><span class="s">"Large"</span><span class="w">
+</span></span></span><span class="line"><span class="cl"><span class="w"></span><span class="p">};</span><span class="w">
+</span></span></span><span class="line"><span class="cl"><span class="w">
+</span></span></span><span class="line"><span class="cl"><span class="w"></span><span class="fm">println!</span><span class="p">(</span><span class="s">"Current team size : </span><span class="si">{}</span><span class="s">"</span><span class="p">,</span><span class="w"> </span><span class="n">team_size</span><span class="p">);</span><span class="w"> </span><span class="c1">// Current team size : Medium
+</span></span></span></code></pre></div><p>βοΈ <strong>Return data type should be the same on each block when using this as an expression.</strong></p>Crateshttps://learning-rust.github.io/docs/crates/Mon, 01 Jan 0001 00:00:00 +0000https://learning-rust.github.io/docs/crates/<p>π Crates are a bit similar to the packages in some other languages. Crates compile individually. If the crate has child file modules, those files will get merged with the crate file and compile as a single unit.</p>
+<p>π A crate can produce an executable/ a binary or a library. <code>src/main.rs</code> is the crate root/ entry point for a binary crate and <code>src/lib.rs</code> is the entry point for a library crate.</p>Custom Error Typeshttps://learning-rust.github.io/docs/custom-error-types/Mon, 01 Jan 0001 00:00:00 +0000https://learning-rust.github.io/docs/custom-error-types/<p>Rust allow us to create our own <code>Err</code> types. We call them β<em>Custom Error Types</em>β.</p>
+<h2 id="error-trait">Error trait</h2>
+<p>As you know <strong>traits define the functionality a type must provide</strong>. But we donβt always need to define new traits for common functionalities, because Rust <strong>standard library provides reusable traits</strong> which can be implemented on our own types. While creating custom error types the <a href="https://doc.rust-lang.org/std/error/trait.Error.html" target="_blank" ><code>std::error::Error</code> trait</a> helps us to convert any type to an <code>Err</code> type.</p>Enumshttps://learning-rust.github.io/docs/enums/Mon, 01 Jan 0001 00:00:00 +0000https://learning-rust.github.io/docs/enums/<p>βοΈ An <strong>enum</strong> is a single type. It contains <strong>variants</strong>, which are possible values of the enum at a given time. For example,</p>
+<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-rust" data-lang="rust"><span class="line"><span class="cl"><span class="k">enum</span> <span class="nc">Day</span><span class="w"> </span><span class="p">{</span><span class="w">
+</span></span></span><span class="line"><span class="cl"><span class="w"> </span><span class="n">Sunday</span><span class="p">,</span><span class="w">
+</span></span></span><span class="line"><span class="cl"><span class="w"> </span><span class="n">Monday</span><span class="p">,</span><span class="w">
+</span></span></span><span class="line"><span class="cl"><span class="w"> </span><span class="n">Tuesday</span><span class="p">,</span><span class="w">
+</span></span></span><span class="line"><span class="cl"><span class="w"> </span><span class="n">Wednesday</span><span class="p">,</span><span class="w">
+</span></span></span><span class="line"><span class="cl"><span class="w"> </span><span class="n">Thursday</span><span class="p">,</span><span class="w">
+</span></span></span><span class="line"><span class="cl"><span class="w"> </span><span class="n">Friday</span><span class="p">,</span><span class="w">
+</span></span></span><span class="line"><span class="cl"><span class="w"> </span><span class="n">Saturday</span><span class="w">
+</span></span></span><span class="line"><span class="cl"><span class="w"></span><span class="p">}</span><span class="w">
+</span></span></span><span class="line"><span class="cl"><span class="w">
+</span></span></span><span class="line"><span class="cl"><span class="w"></span><span class="c1">// The `Day` is the enum
+</span></span></span><span class="line"><span class="cl"><span class="c1">// Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday are the variants
+</span></span></span></code></pre></div><p>βοΈ Variants can be accessed throughΒ :: notation, ex. Day::Sunday</p>
+<p>βοΈ Each enum <strong>variant</strong> can have,</p>Error and None Propagationhttps://learning-rust.github.io/docs/error-and-none-propagation/Mon, 01 Jan 0001 00:00:00 +0000https://learning-rust.github.io/docs/error-and-none-propagation/<p>We should use panics like <code>panic!()</code>, <code>unwrap()</code>, <code>expect()</code> only if we can not handle the situation in a better way. Also if a function contains expressions which can produce either <code>None</code> or <code>Err</code>,</p>
+<ul>
+<li>we can handle them inside the same function. Or,</li>
+<li>we can return <code>None</code> and <code>Err</code> types immediately to the caller. So the caller can decide how to handle them.</li>
+</ul>
+<p>π‘ <code>None</code> types no need to handle by the caller of the function always. But Rustsβ convention to handle <strong><code>Err</code></strong> types is, <strong>return them immediately to the caller to give more control to the caller to decide how to handle them.</strong></p>Functionshttps://learning-rust.github.io/docs/functions/Mon, 01 Jan 0001 00:00:00 +0000https://learning-rust.github.io/docs/functions/<h2 id="named-functions">Named functions</h2>
+<ul>
+<li>Named functions are declared with the keyword <strong><code>fn</code></strong></li>
+<li>When using <strong>arguments</strong>, you <strong>must declare the data types</strong>.</li>
+<li>By default, functions <strong>return an empty <a href="https://learning-rust.github.io/docs/primitive-data-types/#tuple" >tuple</a>/ <code>()</code></strong>. If you want to return a value, the <strong>return type must be specified</strong> after <strong><code>-></code></strong></li>
+</ul>
+<h3 id="i-hello-world">i. Hello world</h3>
+<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-rust" data-lang="rust"><span class="line"><span class="cl"><span class="k">fn</span> <span class="nf">main</span><span class="p">()</span><span class="w"> </span><span class="p">{</span><span class="w">
+</span></span></span><span class="line"><span class="cl"><span class="w"> </span><span class="fm">println!</span><span class="p">(</span><span class="s">"Hello, world!"</span><span class="p">);</span><span class="w">
+</span></span></span><span class="line"><span class="cl"><span class="w"></span><span class="p">}</span><span class="w">
+</span></span></span></code></pre></div><h3 id="ii-passing-arguments">ii. Passing arguments</h3>
+<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-rust" data-lang="rust"><span class="line"><span class="cl"><span class="k">fn</span> <span class="nf">print_sum</span><span class="p">(</span><span class="n">a</span>: <span class="kt">i8</span><span class="p">,</span><span class="w"> </span><span class="n">b</span>: <span class="kt">i8</span><span class="p">)</span><span class="w"> </span><span class="p">{</span><span class="w">
+</span></span></span><span class="line"><span class="cl"><span class="w"> </span><span class="fm">println!</span><span class="p">(</span><span class="s">"sum is: </span><span class="si">{}</span><span class="s">"</span><span class="p">,</span><span class="w"> </span><span class="n">a</span><span class="w"> </span><span class="o">+</span><span class="w"> </span><span class="n">b</span><span class="p">);</span><span class="w">
+</span></span></span><span class="line"><span class="cl"><span class="w"></span><span class="p">}</span><span class="w">
+</span></span></span></code></pre></div><h3 id="iii-returning-values">iii. Returning values</h3>
+<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-rust" data-lang="rust"><span class="line"><span class="cl"><span class="c1">// 01. Without the return keyword. Only the last expression returns.
+</span></span></span><span class="line"><span class="cl"><span class="c1"></span><span class="k">fn</span> <span class="nf">plus_one</span><span class="p">(</span><span class="n">a</span>: <span class="kt">i32</span><span class="p">)</span><span class="w"> </span>-> <span class="kt">i32</span> <span class="p">{</span><span class="w">
+</span></span></span><span class="line"><span class="cl"><span class="w"> </span><span class="n">a</span><span class="w"> </span><span class="o">+</span><span class="w"> </span><span class="mi">1</span><span class="w">
+</span></span></span><span class="line"><span class="cl"><span class="w"> </span><span class="c1">// There is no ending ; in the above line.
+</span></span></span><span class="line"><span class="cl"><span class="c1"></span><span class="w"> </span><span class="c1">// It means this is an expression which equals to `return a + 1;`.
+</span></span></span><span class="line"><span class="cl"><span class="c1"></span><span class="p">}</span><span class="w">
+</span></span></span></code></pre></div><div class="highlight"><pre tabindex="0" class="chroma"><code class="language-rust" data-lang="rust"><span class="line"><span class="cl"><span class="c1">// 02. With the return keyword.
+</span></span></span><span class="line"><span class="cl"><span class="c1"></span><span class="k">fn</span> <span class="nf">plus_two</span><span class="p">(</span><span class="n">a</span>: <span class="kt">i32</span><span class="p">)</span><span class="w"> </span>-> <span class="kt">i32</span> <span class="p">{</span><span class="w">
+</span></span></span><span class="line"><span class="cl"><span class="w"> </span><span class="k">return</span><span class="w"> </span><span class="n">a</span><span class="w"> </span><span class="o">+</span><span class="w"> </span><span class="mi">2</span><span class="p">;</span><span class="w">
+</span></span></span><span class="line"><span class="cl"><span class="w"> </span><span class="c1">// Should use return keyword only on conditional/ early returns.
+</span></span></span><span class="line"><span class="cl"><span class="c1"></span><span class="w"> </span><span class="c1">// Using return keyword in the last expression is a bad practice.
+</span></span></span><span class="line"><span class="cl"><span class="c1"></span><span class="p">}</span><span class="w">
+</span></span></span></code></pre></div><h3 id="iv-function-pointers-usage-as-a-data-type">iv. Function pointers, Usage as a Data Type</h3>
+<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-rust" data-lang="rust"><span class="line"><span class="cl"><span class="k">fn</span> <span class="nf">main</span><span class="p">()</span><span class="w"> </span><span class="p">{</span><span class="w">
+</span></span></span><span class="line"><span class="cl"><span class="w"> </span><span class="c1">// 01. Without type declarations.
+</span></span></span><span class="line"><span class="cl"><span class="c1"></span><span class="w"> </span><span class="kd">let</span><span class="w"> </span><span class="n">p1</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="n">plus_one</span><span class="p">;</span><span class="w">
+</span></span></span><span class="line"><span class="cl"><span class="w"> </span><span class="kd">let</span><span class="w"> </span><span class="n">x</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="n">p1</span><span class="p">(</span><span class="mi">5</span><span class="p">);</span><span class="w"> </span><span class="c1">// 6
+</span></span></span><span class="line"><span class="cl"><span class="c1"></span><span class="w">
+</span></span></span><span class="line"><span class="cl"><span class="w"> </span><span class="c1">// 02. With type declarations.
+</span></span></span><span class="line"><span class="cl"><span class="c1"></span><span class="w"> </span><span class="kd">let</span><span class="w"> </span><span class="n">p1</span>: <span class="nc">fn</span><span class="p">(</span><span class="kt">i32</span><span class="p">)</span><span class="w"> </span>-> <span class="kt">i32</span> <span class="o">=</span><span class="w"> </span><span class="n">plus_one</span><span class="p">;</span><span class="w">
+</span></span></span><span class="line"><span class="cl"><span class="w"> </span><span class="kd">let</span><span class="w"> </span><span class="n">x</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="n">p1</span><span class="p">(</span><span class="mi">5</span><span class="p">);</span><span class="w"> </span><span class="c1">// 6
+</span></span></span><span class="line"><span class="cl"><span class="c1"></span><span class="p">}</span><span class="w">
+</span></span></span><span class="line"><span class="cl"><span class="w">
+</span></span></span><span class="line"><span class="cl"><span class="w"></span><span class="k">fn</span> <span class="nf">plus_one</span><span class="p">(</span><span class="n">a</span>: <span class="kt">i32</span><span class="p">)</span><span class="w"> </span>-> <span class="kt">i32</span> <span class="p">{</span><span class="w">
+</span></span></span><span class="line"><span class="cl"><span class="w"> </span><span class="n">a</span><span class="w"> </span><span class="o">+</span><span class="w"> </span><span class="mi">1</span><span class="w">
+</span></span></span><span class="line"><span class="cl"><span class="w"></span><span class="p">}</span><span class="w">
+</span></span></span></code></pre></div><h2 id="closures">Closures</h2>
+<ul>
+<li>Also known as <strong>anonymous functions</strong> or <strong>lambda functions</strong>.</li>
+<li>The <strong>data types of arguments and returns are optional <a href="#iv-without-optional-type-declarations-creating-and-calling-together" > β°β±α΅</a></strong>.</li>
+</ul>
+<p>Example with a named function, before using closures.</p>Functions (02)https://learning-rust.github.io/docs/functions-02/Mon, 01 Jan 0001 00:00:00 +0000https://learning-rust.github.io/docs/functions-02/<p>Functions are the first line of organization in any program.</p>
+<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-rust" data-lang="rust"><span class="line"><span class="cl"><span class="k">fn</span> <span class="nf">main</span><span class="p">()</span><span class="w"> </span><span class="p">{</span><span class="w">
+</span></span></span><span class="line"><span class="cl"><span class="w"> </span><span class="n">greet</span><span class="p">();</span><span class="w"> </span><span class="c1">// Do one thing
+</span></span></span><span class="line"><span class="cl"><span class="c1"></span><span class="w"> </span><span class="n">ask_location</span><span class="p">();</span><span class="w"> </span><span class="c1">// Do another thing
+</span></span></span><span class="line"><span class="cl"><span class="c1"></span><span class="p">}</span><span class="w">
+</span></span></span><span class="line"><span class="cl"><span class="w">
+</span></span></span><span class="line"><span class="cl"><span class="w"></span><span class="k">fn</span> <span class="nf">greet</span><span class="p">()</span><span class="w"> </span><span class="p">{</span><span class="w">
+</span></span></span><span class="line"><span class="cl"><span class="w"> </span><span class="fm">println!</span><span class="p">(</span><span class="s">"Hello!"</span><span class="p">);</span><span class="w">
+</span></span></span><span class="line"><span class="cl"><span class="w"></span><span class="p">}</span><span class="w">
+</span></span></span><span class="line"><span class="cl"><span class="w">
+</span></span></span><span class="line"><span class="cl"><span class="w"></span><span class="k">fn</span> <span class="nf">ask_location</span><span class="p">()</span><span class="w"> </span><span class="p">{</span><span class="w">
+</span></span></span><span class="line"><span class="cl"><span class="w"> </span><span class="fm">println!</span><span class="p">(</span><span class="s">"Where are you from?"</span><span class="p">);</span><span class="w">
+</span></span></span><span class="line"><span class="cl"><span class="w"></span><span class="p">}</span><span class="w">
+</span></span></span></code></pre></div><p>We can add unit tests in the same file.</p>
+<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-rust" data-lang="rust"><span class="line"><span class="cl"><span class="k">fn</span> <span class="nf">main</span><span class="p">()</span><span class="w"> </span><span class="p">{</span><span class="w">
+</span></span></span><span class="line"><span class="cl"><span class="w"> </span><span class="n">greet</span><span class="p">();</span><span class="w">
+</span></span></span><span class="line"><span class="cl"><span class="w"></span><span class="p">}</span><span class="w">
+</span></span></span><span class="line"><span class="cl"><span class="w">
+</span></span></span><span class="line"><span class="cl"><span class="w"></span><span class="k">fn</span> <span class="nf">greet</span><span class="p">()</span><span class="w"> </span>-> <span class="nb">String</span> <span class="p">{</span><span class="w">
+</span></span></span><span class="line"><span class="cl"><span class="w"> </span><span class="s">"Hello, world!"</span><span class="p">.</span><span class="n">to_string</span><span class="p">()</span><span class="w">
+</span></span></span><span class="line"><span class="cl"><span class="w"></span><span class="p">}</span><span class="w">
+</span></span></span><span class="line"><span class="cl"><span class="w">
+</span></span></span><span class="line"><span class="cl"><span class="w"></span><span class="cp">#[test]</span><span class="w"> </span><span class="c1">// Test attribute indicates this is a test function
+</span></span></span><span class="line"><span class="cl"><span class="c1"></span><span class="k">fn</span> <span class="nf">test_greet</span><span class="p">()</span><span class="w"> </span><span class="p">{</span><span class="w">
+</span></span></span><span class="line"><span class="cl"><span class="w"> </span><span class="fm">assert_eq!</span><span class="p">(</span><span class="s">"Hello, world!"</span><span class="p">,</span><span class="w"> </span><span class="n">greet</span><span class="p">())</span><span class="w">
+</span></span></span><span class="line"><span class="cl"><span class="w"></span><span class="p">}</span><span class="w">
+</span></span></span><span class="line"><span class="cl"><span class="w">
+</span></span></span><span class="line"><span class="cl"><span class="w"></span><span class="c1">// π‘ Always put test functions inside a tests module with #[cfg(test)] attribute.
+</span></span></span><span class="line"><span class="cl"><span class="c1">// cfg(test) module compiles only when running tests. We discuss more about this in the next section.
+</span></span></span></code></pre></div><blockquote>
+<p>π An <a href="https://doc.rust-lang.org/reference/attributes.html" target="_blank" >attribute</a> is a general, free-form <strong>metadatum</strong> that is interpreted according to name, convention, and language and compiler version.</p>Genericshttps://learning-rust.github.io/docs/generics/Mon, 01 Jan 0001 00:00:00 +0000https://learning-rust.github.io/docs/generics/<blockquote>
+<p><a href="https://doc.rust-lang.org/beta/book/first-edition/generics.html" target="_blank" >π</a> Sometimes, when writing a function or data type, we may want it to work for multiple types of arguments. In Rust, we can do this with generics.</p></blockquote>
+<p>π The concept is, instead of declaring a specific data type we use an uppercase letter(or <a href="https://en.wikipedia.org/wiki/Camel_case" target="_blank" >PascalCase</a> identifier). ex, <strong>instead of xΒ : u8</strong> we use <strong>xΒ : T</strong>Β . but we have to inform to the compiler that T is a generic type(can be any type) by adding <code><T></code> at first.</p>Hello Worldhttps://learning-rust.github.io/docs/hello-world/Mon, 01 Jan 0001 00:00:00 +0000https://learning-rust.github.io/docs/hello-world/<h2 id="hello-world">Hello, World!</h2>
+<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-rust" data-lang="rust"><span class="line"><span class="cl"><span class="k">fn</span> <span class="nf">main</span><span class="p">()</span><span class="w"> </span><span class="p">{</span><span class="w">
+</span></span></span><span class="line"><span class="cl"><span class="w"> </span><span class="fm">println!</span><span class="p">(</span><span class="s">"Hello, world!"</span><span class="p">);</span><span class="w">
+</span></span></span><span class="line"><span class="cl"><span class="w"></span><span class="p">}</span><span class="w">
+</span></span></span></code></pre></div><p><code>fn</code> means function. The <code>main</code> function is the beginning of every Rust program.<br>
+<code>println!()</code> prints text to the console and its <code>!</code> indicates that itβs a <a href="https://doc.rust-lang.org/book/ch19-06-macros.html" target="_blank" >macro</a> rather than a function.</p>
+<blockquote>
+<p>π‘ Rust files should have <code>.rs</code> file extension and if youβre using more than one word for the file name, follow the <a href="https://en.wikipedia.org/wiki/Snake_case" target="_blank" >snake_case</a> convention.</p></blockquote>
+<ul>
+<li>Save the above code in <code>file.rs</code> , but it can be any name with <code>.rs</code> extension.</li>
+<li>Compile it with <code>rustc file.rs</code></li>
+<li>Execute it with <code>./file</code> on Linux and Mac or <code>file.exe</code> on Windows</li>
+</ul>
+<h2 id="rust-playground">Rust Playground</h2>
+<p><a href="https://play.rust-lang.org/" target="_blank" >Rust Playground</a> is a web interface for running Rust code.</p>Impls & Traitshttps://learning-rust.github.io/docs/impls-and-traits/Mon, 01 Jan 0001 00:00:00 +0000https://learning-rust.github.io/docs/impls-and-traits/<p>π‘ When we discussed about <strong>C-like structs</strong>, I mentioned that those are <strong>similar to classes</strong> in OOP languages <strong>but without their methods</strong>. <strong>impls</strong> are <strong>used to define methods</strong> for Rust structs and enums.</p>
+<p>π‘ <strong>Traits</strong> are kind of <strong>similar to interfaces</strong> in OOP languages. They are used to define the functionality a type must provide. Multiple traits can be implemented for a single type.</p>
+<p>βοΈοΈ But traits <strong>can also include default implementations of methods</strong>. Default methods can be overridden when implementing types.</p>Installationhttps://learning-rust.github.io/docs/installation/Mon, 01 Jan 0001 00:00:00 +0000https://learning-rust.github.io/docs/installation/<h2 id="rustup">Rustup</h2>
+<p>There are many ways to install Rust on your system. For the moment the official way to install Rust is using <a href="https://rustup.rs/" target="_blank" >Rustup</a>.</p>
+<p><a href="https://rust-lang.github.io/rustup/index.html" target="_blank" >π</a> Rustup installs The Rust Programming Language from the official release channels, enabling you to easily switch between <strong>stable, beta, and nightly</strong> compilers and keep them updated. It also makes cross-compiling simpler with binary builds of the standard library for common platforms.</p>
+<p><a href="https://rust-lang.github.io/rustup/installation/index.html" target="_blank" >π</a> Rustup installs <strong><code>rustc</code>, <code>cargo</code>, <code>rustup</code></strong> and other standard tools to Cargo’s <code>bin</code> directory. On Unix it is located at <code>$HOME/.cargo/bin</code> and on Windows at <code>%USERPROFILE%\.cargo\bin</code>. This is the same directory that <code>cargo install</code> will install Rust programs and Cargo plugins.</p>Lifetimeshttps://learning-rust.github.io/docs/lifetimes/Mon, 01 Jan 0001 00:00:00 +0000https://learning-rust.github.io/docs/lifetimes/<p>When we are dealing with references, we have to make sure that the referencing data stay alive until we stop using the references.</p>
+<p>Think,</p>
+<ul>
+<li>We have a <strong>variable binding</strong>, <code>a</code>.</li>
+<li>We are <strong>referencing</strong> the value of <code>a</code>, <strong>from another variable binding</strong> <code>x</code>.
+We have to make sure that <strong><code>a</code> lives until we stop using <code>x</code></strong>.</li>
+</ul>
+<blockquote>
+<p>π <strong>Memory management</strong> is a form of resource management applied to computer memory. Up until the mid-1990s, the majority of programming languages used <strong>Manual Memory Management</strong> which <strong>requires the programmer to give manual instructions</strong> to identify and deallocate unused objects/ garbage. Around 1959 John McCarthy invented <strong>Garbage collection</strong>(GC), a form of <strong>Automatic Memory Management</strong>(AMM). It determines what memory is no longer used and frees it automatically instead of relying on the programmer. However <strong>Objective-C and Swift</strong> provide similar functionality through <strong>Automatic Reference Counting</strong>(ARC).</p>Moduleshttps://learning-rust.github.io/docs/modules/Mon, 01 Jan 0001 00:00:00 +0000https://learning-rust.github.io/docs/modules/<h2 id="01-in-the-same-file">01. In the same file</h2>
+<p>Related code and data are grouped into a module and stored in the same file.</p>
+<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-rust" data-lang="rust"><span class="line"><span class="cl"><span class="k">fn</span> <span class="nf">main</span><span class="p">()</span><span class="w"> </span><span class="p">{</span><span class="w">
+</span></span></span><span class="line"><span class="cl"><span class="w"> </span><span class="n">greetings</span>::<span class="n">hello</span><span class="p">();</span><span class="w">
+</span></span></span><span class="line"><span class="cl"><span class="w"></span><span class="p">}</span><span class="w">
+</span></span></span><span class="line"><span class="cl"><span class="w">
+</span></span></span><span class="line"><span class="cl"><span class="w"></span><span class="k">mod</span> <span class="nn">greetings</span><span class="w"> </span><span class="p">{</span><span class="w">
+</span></span></span><span class="line"><span class="cl"><span class="w"> </span><span class="c1">// βοΈ By default, everything inside a module is private
+</span></span></span><span class="line"><span class="cl"><span class="c1"></span><span class="w"> </span><span class="k">pub</span><span class="w"> </span><span class="k">fn</span> <span class="nf">hello</span><span class="p">()</span><span class="w"> </span><span class="p">{</span><span class="w"> </span><span class="c1">// βοΈ So function has to be public to access from outside
+</span></span></span><span class="line"><span class="cl"><span class="c1"></span><span class="w"> </span><span class="fm">println!</span><span class="p">(</span><span class="s">"Hello, world!"</span><span class="p">);</span><span class="w">
+</span></span></span><span class="line"><span class="cl"><span class="w"> </span><span class="p">}</span><span class="w">
+</span></span></span><span class="line"><span class="cl"><span class="w"></span><span class="p">}</span><span class="w">
+</span></span></span></code></pre></div><p>Modules can also be nested.</p>
+<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-rust" data-lang="rust"><span class="line"><span class="cl"><span class="k">fn</span> <span class="nf">main</span><span class="p">()</span><span class="w"> </span><span class="p">{</span><span class="w">
+</span></span></span><span class="line"><span class="cl"><span class="w"> </span><span class="n">phrases</span>::<span class="n">greetings</span>::<span class="n">hello</span><span class="p">();</span><span class="w">
+</span></span></span><span class="line"><span class="cl"><span class="w"></span><span class="p">}</span><span class="w">
+</span></span></span><span class="line"><span class="cl"><span class="w">
+</span></span></span><span class="line"><span class="cl"><span class="w"></span><span class="k">mod</span> <span class="nn">phrases</span><span class="w"> </span><span class="p">{</span><span class="w">
+</span></span></span><span class="line"><span class="cl"><span class="w"> </span><span class="k">pub</span><span class="w"> </span><span class="k">mod</span> <span class="nn">greetings</span><span class="w"> </span><span class="p">{</span><span class="w">
+</span></span></span><span class="line"><span class="cl"><span class="w"> </span><span class="k">pub</span><span class="w"> </span><span class="k">fn</span> <span class="nf">hello</span><span class="p">()</span><span class="w"> </span><span class="p">{</span><span class="w">
+</span></span></span><span class="line"><span class="cl"><span class="w"> </span><span class="fm">println!</span><span class="p">(</span><span class="s">"Hello, world!"</span><span class="p">);</span><span class="w">
+</span></span></span><span class="line"><span class="cl"><span class="w"> </span><span class="p">}</span><span class="w">
+</span></span></span><span class="line"><span class="cl"><span class="w"> </span><span class="p">}</span><span class="w">
+</span></span></span><span class="line"><span class="cl"><span class="w"></span><span class="p">}</span><span class="w">
+</span></span></span></code></pre></div><p>Private functions can be called from the same module or from a child module.</p>Operatorshttps://learning-rust.github.io/docs/operators/Mon, 01 Jan 0001 00:00:00 +0000https://learning-rust.github.io/docs/operators/<ul>
+<li>
+<h2 id="arithmetic-operators">Arithmetic Operators</h2>
+</li>
+</ul>
+<p><code>+ - * / %</code></p>
+<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-rust" data-lang="rust"><span class="line"><span class="cl"><span class="kd">let</span><span class="w"> </span><span class="n">a</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="mi">5</span><span class="p">;</span><span class="w">
+</span></span></span><span class="line"><span class="cl"><span class="w"></span><span class="kd">let</span><span class="w"> </span><span class="n">b</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="n">a</span><span class="w"> </span><span class="o">+</span><span class="w"> </span><span class="mi">1</span><span class="p">;</span><span class="w"> </span><span class="c1">//6
+</span></span></span><span class="line"><span class="cl"><span class="c1"></span><span class="kd">let</span><span class="w"> </span><span class="n">c</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="n">a</span><span class="w"> </span><span class="o">-</span><span class="w"> </span><span class="mi">1</span><span class="p">;</span><span class="w"> </span><span class="c1">//4
+</span></span></span><span class="line"><span class="cl"><span class="c1"></span><span class="kd">let</span><span class="w"> </span><span class="n">d</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="n">a</span><span class="w"> </span><span class="o">*</span><span class="w"> </span><span class="mi">2</span><span class="p">;</span><span class="w"> </span><span class="c1">//10
+</span></span></span><span class="line"><span class="cl"><span class="c1"></span><span class="kd">let</span><span class="w"> </span><span class="n">e</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="n">a</span><span class="w"> </span><span class="o">/</span><span class="w"> </span><span class="mi">2</span><span class="p">;</span><span class="w"> </span><span class="c1">// βοΈ 2 not 2.5
+</span></span></span><span class="line"><span class="cl"><span class="c1"></span><span class="kd">let</span><span class="w"> </span><span class="n">f</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="n">a</span><span class="w"> </span><span class="o">%</span><span class="w"> </span><span class="mi">2</span><span class="p">;</span><span class="w"> </span><span class="c1">//1
+</span></span></span><span class="line"><span class="cl"><span class="c1"></span><span class="w">
+</span></span></span><span class="line"><span class="cl"><span class="w"></span><span class="kd">let</span><span class="w"> </span><span class="n">g</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="mf">5.0</span><span class="w"> </span><span class="o">/</span><span class="w"> </span><span class="mf">2.0</span><span class="p">;</span><span class="w"> </span><span class="c1">//2.5
+</span></span></span></code></pre></div><ul>
+<li>
+<h2 id="comparison-operators">Comparison Operators</h2>
+</li>
+</ul>
+<p><code>== != < > <= >=</code></p>
+<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-rust" data-lang="rust"><span class="line"><span class="cl"><span class="kd">let</span><span class="w"> </span><span class="n">a</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="mi">1</span><span class="p">;</span><span class="w">
+</span></span></span><span class="line"><span class="cl"><span class="w"></span><span class="kd">let</span><span class="w"> </span><span class="n">b</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="mi">2</span><span class="p">;</span><span class="w">
+</span></span></span><span class="line"><span class="cl"><span class="w">
+</span></span></span><span class="line"><span class="cl"><span class="w"></span><span class="kd">let</span><span class="w"> </span><span class="n">c</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="n">a</span><span class="w"> </span><span class="o">==</span><span class="w"> </span><span class="n">b</span><span class="p">;</span><span class="w"> </span><span class="c1">//false
+</span></span></span><span class="line"><span class="cl"><span class="c1"></span><span class="kd">let</span><span class="w"> </span><span class="n">d</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="n">a</span><span class="w"> </span><span class="o">!=</span><span class="w"> </span><span class="n">b</span><span class="p">;</span><span class="w"> </span><span class="c1">//true
+</span></span></span><span class="line"><span class="cl"><span class="c1"></span><span class="kd">let</span><span class="w"> </span><span class="n">e</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="n">a</span><span class="w"> </span><span class="o"><</span><span class="w"> </span><span class="n">b</span><span class="p">;</span><span class="w"> </span><span class="c1">//true
+</span></span></span><span class="line"><span class="cl"><span class="c1"></span><span class="kd">let</span><span class="w"> </span><span class="n">f</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="n">a</span><span class="w"> </span><span class="o">></span><span class="w"> </span><span class="n">b</span><span class="p">;</span><span class="w"> </span><span class="c1">//false
+</span></span></span><span class="line"><span class="cl"><span class="c1"></span><span class="kd">let</span><span class="w"> </span><span class="n">g</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="n">a</span><span class="w"> </span><span class="o"><=</span><span class="w"> </span><span class="n">a</span><span class="p">;</span><span class="w"> </span><span class="c1">//true
+</span></span></span><span class="line"><span class="cl"><span class="c1"></span><span class="kd">let</span><span class="w"> </span><span class="n">h</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="n">a</span><span class="w"> </span><span class="o">>=</span><span class="w"> </span><span class="n">a</span><span class="p">;</span><span class="w"> </span><span class="c1">//true
+</span></span></span><span class="line"><span class="cl"><span class="c1"></span><span class="w">
+</span></span></span><span class="line"><span class="cl"><span class="w"></span><span class="c1">// π
+</span></span></span><span class="line"><span class="cl"><span class="c1"></span><span class="kd">let</span><span class="w"> </span><span class="n">i</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="kc">true</span><span class="w"> </span><span class="o">></span><span class="w"> </span><span class="kc">false</span><span class="p">;</span><span class="w"> </span><span class="c1">//true
+</span></span></span><span class="line"><span class="cl"><span class="c1"></span><span class="kd">let</span><span class="w"> </span><span class="n">j</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="sc">'a'</span><span class="w"> </span><span class="o">></span><span class="w"> </span><span class="sc">'A'</span><span class="p">;</span><span class="w"> </span><span class="c1">//true
+</span></span></span></code></pre></div><ul>
+<li>
+<h2 id="logical-operators">Logical Operators</h2>
+</li>
+</ul>
+<p><code>! && ||</code></p>Option and Resulthttps://learning-rust.github.io/docs/option-and-result/Mon, 01 Jan 0001 00:00:00 +0000https://learning-rust.github.io/docs/option-and-result/<h2 id="why-option-and-result">Why Option and Result?</h2>
+<p>Many languages use <strong><code>null</code>\ <code>nil</code>\ <code>undefined</code> types</strong> to represent empty outputs, and <strong><code>Exceptions</code></strong> to handle errors. Rust skips using both, especially to prevent issues like <strong>null pointer exceptions, sensitive data leakages through exceptions</strong>, etc. Instead, Rust provides two special <strong>generic enums</strong>;<code>Option</code> and <code>Result</code> to deal with above cases.</p>
+<blockquote>
+<p>π In the previous sections, we have discussed about the basics of <a href="https://learning-rust.github.io/docs/enums" >enums</a>, <a href="https://learning-rust.github.io/docs/generics" >generics</a> and <a href="https://learning-rust.github.io/docs/generics/#generalizing-enums" ><code>Result</code> & <code>Option</code> types</a>.</p>Overviewhttps://learning-rust.github.io/docs/overview/Mon, 01 Jan 0001 00:00:00 +0000https://learning-rust.github.io/docs/overview/<h2 id="about-me">About me</h2>
+<blockquote>
+<p>π§βπ» I am an expat working in Singapore as a Go Backend and DevOps Engineer. Feel free to reach out if you find any mistakes or anything that needs to be changed, including spelling or grammar errors. Alternatively, you can create a pull request, open an issue, or <a href="https://gist.github.com/dumindu/00a0be2d175ed5ff3bc3c17bbf1ca5b6" target="_blank" >share your awesome ideas in this gist</a>. Good luck with learning Rust!</p></blockquote>
+<p><a href="https://github.com/learning-rust/learning-rust.github.io" target="_blank" ><img src="https://img.shields.io/github/stars/learning-rust/learning-rust.github.io?style=for-the-badge&logo=rust&label=learning-rust.github.io&logoColor=333333&labelColor=f9f9f9&color=F46623" alt="learning-rust.github.io"></a>
+<a href="https://learning-cloud-native-go.github.io" target="_blank" ><img src="https://img.shields.io/github/stars/learning-cloud-native-go/learning-cloud-native-go.github.io?style=for-the-badge&logo=go&logoColor=333333&label=learning-cloud-native-go.github.io&labelColor=f9f9f9&color=00ADD8" alt="learning-cloud-native-go.github.io"></a></p>
+<p><a href="https://github.com/dumindu" target="_blank" ><img src="https://img.shields.io/badge/dumindu-866ee7?style=for-the-badge&logo=GitHub&logoColor=333333&labelColor=f9f9f9" alt="github.com"></a>
+<a href="https://www.buymeacoffee.com/dumindu" target="_blank" ><img src="https://img.shields.io/badge/Buy%20me%20a%20coffee-dumindu-FFDD00?style=for-the-badge&logo=buymeacoffee&logoColor=333333&labelColor=f9f9f9" alt="buymeacoffee"></a></p>
+<h2 id="overview">Overview</h2>
+<p>This publication has its origins in the posts I authored on Medium at <a href="https://medium.com/learning-rust" target="_blank" >https://medium.com/learning-rust</a>. However, please note that I have ceased updating the Medium posts. All current and future updates, new content, code, and grammar fixes will be exclusively maintained and released here, <a href="https://learning-rust.github.io" target="_blank" >https://learning-rust.github.io</a>.</p>Ownershiphttps://learning-rust.github.io/docs/ownership/Mon, 01 Jan 0001 00:00:00 +0000https://learning-rust.github.io/docs/ownership/<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-rust" data-lang="rust"><span class="line"><span class="cl"><span class="k">fn</span> <span class="nf">main</span><span class="p">()</span><span class="w"> </span><span class="p">{</span><span class="w">
+</span></span></span><span class="line"><span class="cl"><span class="w"> </span><span class="kd">let</span><span class="w"> </span><span class="n">a</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="p">[</span><span class="mi">1</span><span class="p">,</span><span class="w"> </span><span class="mi">2</span><span class="p">,</span><span class="w"> </span><span class="mi">3</span><span class="p">];</span><span class="w">
+</span></span></span><span class="line"><span class="cl"><span class="w"> </span><span class="kd">let</span><span class="w"> </span><span class="n">b</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="n">a</span><span class="p">;</span><span class="w">
+</span></span></span><span class="line"><span class="cl"><span class="w"> </span><span class="fm">println!</span><span class="p">(</span><span class="s">"</span><span class="si">{:?}</span><span class="s"> </span><span class="si">{:?}</span><span class="s">"</span><span class="p">,</span><span class="w"> </span><span class="n">a</span><span class="p">,</span><span class="w"> </span><span class="n">b</span><span class="p">);</span><span class="w"> </span><span class="c1">// [1, 2, 3] [1, 2, 3]
+</span></span></span><span class="line"><span class="cl"><span class="c1"></span><span class="p">}</span><span class="w">
+</span></span></span><span class="line"><span class="cl"><span class="w">
+</span></span></span><span class="line"><span class="cl"><span class="w"></span><span class="k">fn</span> <span class="nf">main</span><span class="p">()</span><span class="w"> </span><span class="p">{</span><span class="w">
+</span></span></span><span class="line"><span class="cl"><span class="w"> </span><span class="kd">let</span><span class="w"> </span><span class="n">a</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="fm">vec!</span><span class="p">[</span><span class="mi">1</span><span class="p">,</span><span class="w"> </span><span class="mi">2</span><span class="p">,</span><span class="w"> </span><span class="mi">3</span><span class="p">];</span><span class="w">
+</span></span></span><span class="line"><span class="cl"><span class="w"> </span><span class="kd">let</span><span class="w"> </span><span class="n">b</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="n">a</span><span class="p">;</span><span class="w">
+</span></span></span><span class="line"><span class="cl"><span class="w"> </span><span class="fm">println!</span><span class="p">(</span><span class="s">"</span><span class="si">{:?}</span><span class="s"> </span><span class="si">{:?}</span><span class="s">"</span><span class="p">,</span><span class="w"> </span><span class="n">a</span><span class="p">,</span><span class="w"> </span><span class="n">b</span><span class="p">);</span><span class="w"> </span><span class="c1">// Error; use of moved value: `a`
+</span></span></span><span class="line"><span class="cl"><span class="c1"></span><span class="p">}</span><span class="w">
+</span></span></span></code></pre></div><p>In the above examples, we are just trying to <strong>assign the value of <code>a</code> to <code>b</code></strong> . Almost the same code in both code blocks, but having <strong>two different data types</strong>. And the second one gives an error. This is because of the <strong>Ownership</strong>.</p>Panickinghttps://learning-rust.github.io/docs/panicking/Mon, 01 Jan 0001 00:00:00 +0000https://learning-rust.github.io/docs/panicking/<h2 id="panic">panic!()</h2>
+<ul>
+<li>In some cases, when an error occurs we can not do anything to handle it, <strong>if the error is something which should not have happened</strong>. In other words, if itβs an <strong>unrecoverable error</strong>.</li>
+<li>Also <strong>when we are not using a feature-rich debugger or proper logs</strong>, sometimes we need to <strong>debug the code by quitting the program from a specific line of code</strong> by printing out a specific message or a value of a variable binding to understand the current flow of the program.
+For above cases, we can use <code>panic!</code> macro.</li>
+</ul>
+<p>β <code>panic!()</code> runs <strong>thread based</strong>. One thread can be panicked, while other threads are running.</p>Primitive Data Typeshttps://learning-rust.github.io/docs/primitive-data-types/Mon, 01 Jan 0001 00:00:00 +0000https://learning-rust.github.io/docs/primitive-data-types/<ul>
+<li>
+<h2 id="bool">bool</h2>
+</li>
+</ul>
+<p>true or false</p>
+<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-rust" data-lang="rust"><span class="line"><span class="cl"><span class="kd">let</span><span class="w"> </span><span class="n">x</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="kc">true</span><span class="p">;</span><span class="w">
+</span></span></span><span class="line"><span class="cl"><span class="w"></span><span class="kd">let</span><span class="w"> </span><span class="n">y</span>: <span class="kt">bool</span> <span class="o">=</span><span class="w"> </span><span class="kc">false</span><span class="p">;</span><span class="w">
+</span></span></span><span class="line"><span class="cl"><span class="w">
+</span></span></span><span class="line"><span class="cl"><span class="w"></span><span class="c1">// βοΈ no TRUE, FALSE, 1, 0
+</span></span></span></code></pre></div><ul>
+<li>
+<h2 id="char">char</h2>
+</li>
+</ul>
+<p>A single Unicode scalar value</p>
+<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-rust" data-lang="rust"><span class="line"><span class="cl"><span class="kd">let</span><span class="w"> </span><span class="n">x</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="sc">'x'</span><span class="p">;</span><span class="w">
+</span></span></span><span class="line"><span class="cl"><span class="w"></span><span class="kd">let</span><span class="w"> </span><span class="n">y</span>: <span class="kt">char</span> <span class="o">=</span><span class="w"> </span><span class="sc">'π'</span><span class="p">;</span><span class="w">
+</span></span></span><span class="line"><span class="cl"><span class="w">
+</span></span></span><span class="line"><span class="cl"><span class="w"></span><span class="c1">// βοΈ no "x", only single quotes
+</span></span></span></code></pre></div><p>Because of Unicode support, char is not a single byte, but four(32 bits).</p>
+<ul>
+<li>
+<h2 id="i8-i16-i32-i64-i128">i8, i16, i32, i64, i128</h2>
+</li>
+</ul>
+<p>8, 16, 32, 64 and 128 bit fixed sized signed(+/-) integer types</p>Smart Compilerhttps://learning-rust.github.io/docs/smart-compiler/Mon, 01 Jan 0001 00:00:00 +0000https://learning-rust.github.io/docs/smart-compiler/<h2 id="why-compiler">Why Compiler?</h2>
+<p>The Rust compiler does the most significant job to prevent errors in Rust programs. It <strong>analyzes the code at compile-time</strong> and issues warnings, if the code does not follow memory management rules or lifetime annotations correctly.</p>
+<p>For example,</p>
+<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-rust" data-lang="rust"><span class="line"><span class="cl"><span class="cp">#[allow(unused_variables)]</span><span class="w"> </span><span class="c1">//π‘ A lint attribute used to suppress the warning; unused variable: `b`
+</span></span></span><span class="line"><span class="cl"><span class="c1"></span><span class="k">fn</span> <span class="nf">main</span><span class="p">()</span><span class="w"> </span><span class="p">{</span><span class="w">
+</span></span></span><span class="line"><span class="cl"><span class="w"> </span><span class="kd">let</span><span class="w"> </span><span class="n">a</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="fm">vec!</span><span class="p">[</span><span class="mi">1</span><span class="p">,</span><span class="w"> </span><span class="mi">2</span><span class="p">,</span><span class="w"> </span><span class="mi">3</span><span class="p">];</span><span class="w">
+</span></span></span><span class="line"><span class="cl"><span class="w"> </span><span class="kd">let</span><span class="w"> </span><span class="n">b</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="n">a</span><span class="p">;</span><span class="w">
+</span></span></span><span class="line"><span class="cl"><span class="w">
+</span></span></span><span class="line"><span class="cl"><span class="w"> </span><span class="fm">println!</span><span class="p">(</span><span class="s">"</span><span class="si">{:?}</span><span class="s">"</span><span class="p">,</span><span class="w"> </span><span class="n">a</span><span class="p">);</span><span class="w">
+</span></span></span><span class="line"><span class="cl"><span class="w"></span><span class="p">}</span><span class="w">
+</span></span></span><span class="line"><span class="cl"><span class="w">
+</span></span></span><span class="line"><span class="cl"><span class="w">
+</span></span></span><span class="line"><span class="cl"><span class="w"></span><span class="c1">// ------ Compile-time error ------
+</span></span></span><span class="line"><span class="cl"><span class="c1"></span><span class="n">error</span><span class="p">[</span><span class="n">E0382</span><span class="p">]</span>: <span class="nc">use</span><span class="w"> </span><span class="n">of</span><span class="w"> </span><span class="n">moved</span><span class="w"> </span><span class="n">value</span>: <span class="err">`</span><span class="n">a</span><span class="err">`</span><span class="w">
+</span></span></span><span class="line"><span class="cl"><span class="w"> </span><span class="o">-</span>-> <span class="nc">src</span><span class="o">/</span><span class="n">main</span><span class="p">.</span><span class="n">rs</span>:<span class="mi">6</span>:<span class="mi">22</span><span class="w">
+</span></span></span><span class="line"><span class="cl"><span class="w"> </span><span class="o">|</span><span class="w">
+</span></span></span><span class="line"><span class="cl"><span class="w"></span><span class="mi">3</span><span class="w"> </span><span class="o">|</span><span class="w"> </span><span class="kd">let</span><span class="w"> </span><span class="n">b</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="n">a</span><span class="p">;</span><span class="w">
+</span></span></span><span class="line"><span class="cl"><span class="w"> </span><span class="o">|</span><span class="w"> </span><span class="o">-</span><span class="w"> </span><span class="n">value</span><span class="w"> </span><span class="n">moved</span><span class="w"> </span><span class="n">here</span><span class="w">
+</span></span></span><span class="line"><span class="cl"><span class="w"></span><span class="mi">4</span><span class="w"> </span><span class="o">|</span><span class="w">
+</span></span></span><span class="line"><span class="cl"><span class="w"></span><span class="mi">5</span><span class="w"> </span><span class="o">|</span><span class="w"> </span><span class="fm">println!</span><span class="p">(</span><span class="s">"</span><span class="si">{:?}</span><span class="s">"</span><span class="p">,</span><span class="w"> </span><span class="n">a</span><span class="p">);</span><span class="w">
+</span></span></span><span class="line"><span class="cl"><span class="w"> </span><span class="o">|</span><span class="w"> </span><span class="o">^</span><span class="w"> </span><span class="n">value</span><span class="w"> </span><span class="n">used</span><span class="w"> </span><span class="n">here</span><span class="w"> </span><span class="n">after</span><span class="w"> </span><span class="k">move</span><span class="w">
+</span></span></span><span class="line"><span class="cl"><span class="w"> </span><span class="o">|</span><span class="w">
+</span></span></span><span class="line"><span class="cl"><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="n">note</span>: <span class="nc">move</span><span class="w"> </span><span class="n">occurs</span><span class="w"> </span><span class="n">because</span><span class="w"> </span><span class="err">`</span><span class="n">a</span><span class="err">`</span><span class="w"> </span><span class="n">has</span><span class="w"> </span><span class="k">type</span> <span class="err">`</span><span class="n">std</span>::<span class="n">vec</span>::<span class="nb">Vec</span><span class="o"><</span><span class="kt">i32</span><span class="o">></span><span class="err">`</span><span class="p">,</span><span class="w"> </span><span class="n">which</span><span class="w"> </span><span class="n">does</span><span class="w"> </span><span class="n">not</span><span class="w"> </span><span class="n">implement</span><span class="w"> </span><span class="n">the</span><span class="w"> </span><span class="err">`</span><span class="nb">Copy</span><span class="err">`</span><span class="w"> </span><span class="k">trait</span><span class="w">
+</span></span></span><span class="line"><span class="cl"><span class="w">
+</span></span></span><span class="line"><span class="cl"><span class="w"></span><span class="n">error</span>: <span class="nc">aborting</span><span class="w"> </span><span class="n">due</span><span class="w"> </span><span class="n">to</span><span class="w"> </span><span class="n">previous</span><span class="w"> </span><span class="n">error</span><span class="w">
+</span></span></span><span class="line"><span class="cl"><span class="w"></span><span class="n">For</span><span class="w"> </span><span class="n">more</span><span class="w"> </span><span class="n">information</span><span class="w"> </span><span class="n">about</span><span class="w"> </span><span class="n">this</span><span class="w"> </span><span class="n">error</span><span class="p">,</span><span class="w"> </span><span class="kr">try</span><span class="w"> </span><span class="err">`</span><span class="n">rustc</span><span class="w"> </span><span class="o">--</span><span class="n">explain</span><span class="w"> </span><span class="n">E0382</span><span class="err">`</span><span class="p">.</span><span class="w">
+</span></span></span><span class="line"><span class="cl"><span class="w">
+</span></span></span><span class="line"><span class="cl"><span class="w"></span><span class="c1">// β instead using #[allow(unused_variables)], consider using "let _b = a;" in line 4.
+</span></span></span><span class="line"><span class="cl"><span class="c1">// Also you can use "let _ =" to completely ignore return values
+</span></span></span></code></pre></div><blockquote>
+<p>π In the previous sections, we have discussed memory management concepts like <a href="https://learning-rust.github.io/docs/ownership" >ownership</a>, <a href="https://learning-rust.github.io/docs/borrowing" >borrowing</a>, <a href="https://learning-rust.github.io/docs/lifetimes" >lifetimes</a> and etc.</p>STD, Primitives and Preludeshttps://learning-rust.github.io/docs/std-primitives-and-preludes/Mon, 01 Jan 0001 00:00:00 +0000https://learning-rust.github.io/docs/std-primitives-and-preludes/<p>βοΈ In Rust, language elements are implemented by not only <strong><code>std</code> library</strong> crate but also <strong>compiler</strong> as well. Examples,</p>
+<ul>
+<li><strong><a href="https://doc.rust-lang.org/std/#primitives" target="_blank" >Primitives</a></strong>: Defined by the compiler and methods are implemented by <code>std</code> library directly on primitives.</li>
+<li><strong><a href="https://doc.rust-lang.org/std/#macros" target="_blank" >Standard Macros</a></strong>: Defined by both compiler and <code>std</code></li>
+</ul>
+<p>The <strong><code>std</code></strong> library has been divided into <strong><a href="https://doc.rust-lang.org/std/#modules" target="_blank" >modules</a></strong>, according to the main areas each covered.</p>
+<p>βοΈ While primitives are implemented by the <strong>compiler</strong>, the standard library implements the <strong>most useful methods</strong> directly on the primitive types. But some <strong>rarely useful language elements</strong> of some primitives are stored on relevant <strong><code>std</code> modules</strong>. This is why you can see <code>char</code>, <code>str</code> and integer types on both <a href="https://doc.rust-lang.org/std/#primitives" target="_blank" >primitives</a> and <a href="https://doc.rust-lang.org/std/#modules" target="_blank" ><code>std</code> modules</a>.</p>Structshttps://learning-rust.github.io/docs/structs/Mon, 01 Jan 0001 00:00:00 +0000https://learning-rust.github.io/docs/structs/<p>βοΈ Structs are used to <strong>encapsulate related properties</strong> into one unified data type.</p>
+<p>π‘ By convention, the name of the struct should follow <a href="https://en.wikipedia.org/wiki/Camel_case" target="_blank" >PascalCase</a>.</p>
+<p>There are 3 variants of structs,</p>
+<ol>
+<li><strong>C-like structs</strong></li>
+</ol>
+<ul>
+<li>One or more comma-separated name:value pairs</li>
+<li>Brace-enclosed list</li>
+<li>Similar to classes (without its methods) in OOP languages</li>
+<li>Because fields have names, we can access them through dot notation</li>
+</ul>
+<ol start="2">
+<li><strong>Tuple structs</strong></li>
+</ol>
+<ul>
+<li>One or more comma-separated values</li>
+<li>A parenthesized list like tuples</li>
+<li>Looks like a named tuples</li>
+</ul>
+<ol start="3">
+<li><strong>Unit structs</strong></li>
+</ol>
+<ul>
+<li>A struct with no members at all</li>
+<li>It defines a new type but it resembles an empty tuple, ()</li>
+<li>Rarely in use, useful with generics</li>
+</ul>
+<p>βοΈ When regarding OOP in Rust, attributes and methods are placed separately on <strong>structs</strong> and <strong>traits</strong>. Structs contain only attributes, traits contain only methods. They are getting connected via <strong>impls</strong>.</p>Unwrap and Expecthttps://learning-rust.github.io/docs/unwrap-and-expect/Mon, 01 Jan 0001 00:00:00 +0000https://learning-rust.github.io/docs/unwrap-and-expect/<h2 id="unwrap">unwrap()</h2>
+<ul>
+<li>If an <code>Option</code> type has <strong><code>Some</code></strong> value or a <code>Result</code> type has a <strong><code>Ok</code></strong> value, <strong>the value inside them</strong> passes to the next step.</li>
+<li>If the <code>Option</code> type has <strong><code>None</code></strong> value or the <code>Result</code> type has <strong><code>Err</code></strong> value, <strong>program panics</strong>; If <code>Err</code>, panics with the error message.</li>
+</ul>
+<p>The functionality is bit similar to the following codes, which are using <code>match</code> instead <code>unwrap()</code>.</p>
+<p>Example with <code>Option</code> and <code>match</code>, before using <code>unwrap()</code></p>Usehttps://learning-rust.github.io/docs/use/Mon, 01 Jan 0001 00:00:00 +0000https://learning-rust.github.io/docs/use/<p>Let’s see the main usages of the <code>use</code> keyword.</p>
+<h2 id="01-bind-a-full-path-to-a-new-name">01. Bind a full path to a new name</h2>
+<p>Mainly <code>use</code> keyword is used to bind a full path of an element to a new name. So the user doesnβt want to repeat the full path each time.</p>
+<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-rust" data-lang="rust"><span class="line"><span class="cl"><span class="c1">// -- Initial code without the `use` keyword --
+</span></span></span><span class="line"><span class="cl"><span class="c1"></span><span class="k">mod</span> <span class="nn">phrases</span><span class="w"> </span><span class="p">{</span><span class="w">
+</span></span></span><span class="line"><span class="cl"><span class="w"> </span><span class="k">pub</span><span class="w"> </span><span class="k">mod</span> <span class="nn">greetings</span><span class="w"> </span><span class="p">{</span><span class="w">
+</span></span></span><span class="line"><span class="cl"><span class="w"> </span><span class="k">pub</span><span class="w"> </span><span class="k">fn</span> <span class="nf">hello</span><span class="p">()</span><span class="w"> </span><span class="p">{</span><span class="w">
+</span></span></span><span class="line"><span class="cl"><span class="w"> </span><span class="fm">println!</span><span class="p">(</span><span class="s">"Hello, world!"</span><span class="p">);</span><span class="w">
+</span></span></span><span class="line"><span class="cl"><span class="w"> </span><span class="p">}</span><span class="w">
+</span></span></span><span class="line"><span class="cl"><span class="w"> </span><span class="p">}</span><span class="w">
+</span></span></span><span class="line"><span class="cl"><span class="w"></span><span class="p">}</span><span class="w">
+</span></span></span><span class="line"><span class="cl"><span class="w">
+</span></span></span><span class="line"><span class="cl"><span class="w"></span><span class="k">fn</span> <span class="nf">main</span><span class="p">()</span><span class="w"> </span><span class="p">{</span><span class="w">
+</span></span></span><span class="line"><span class="cl"><span class="w"> </span><span class="n">phrases</span>::<span class="n">greetings</span>::<span class="n">hello</span><span class="p">();</span><span class="w"> </span><span class="c1">// Using full path
+</span></span></span><span class="line"><span class="cl"><span class="c1"></span><span class="p">}</span><span class="w">
+</span></span></span><span class="line"><span class="cl"><span class="w">
+</span></span></span><span class="line"><span class="cl"><span class="w">
+</span></span></span><span class="line"><span class="cl"><span class="w"></span><span class="c1">// -- Usage of the `use` keyword --
+</span></span></span><span class="line"><span class="cl"><span class="c1">// 01. Create an alias for module
+</span></span></span><span class="line"><span class="cl"><span class="c1"></span><span class="k">use</span><span class="w"> </span><span class="n">phrases</span>::<span class="n">greetings</span><span class="p">;</span><span class="w">
+</span></span></span><span class="line"><span class="cl"><span class="w"></span><span class="k">fn</span> <span class="nf">main</span><span class="p">()</span><span class="w"> </span><span class="p">{</span><span class="w">
+</span></span></span><span class="line"><span class="cl"><span class="w"> </span><span class="n">greetings</span>::<span class="n">hello</span><span class="p">();</span><span class="w">
+</span></span></span><span class="line"><span class="cl"><span class="w"></span><span class="p">}</span><span class="w">
+</span></span></span><span class="line"><span class="cl"><span class="w">
+</span></span></span><span class="line"><span class="cl"><span class="w"></span><span class="c1">// 02. Create an alias for module elements
+</span></span></span><span class="line"><span class="cl"><span class="c1"></span><span class="k">use</span><span class="w"> </span><span class="n">phrases</span>::<span class="n">greetings</span>::<span class="n">hello</span><span class="p">;</span><span class="w">
+</span></span></span><span class="line"><span class="cl"><span class="w"></span><span class="k">fn</span> <span class="nf">main</span><span class="p">()</span><span class="w"> </span><span class="p">{</span><span class="w">
+</span></span></span><span class="line"><span class="cl"><span class="w"> </span><span class="n">hello</span><span class="p">();</span><span class="w">
+</span></span></span><span class="line"><span class="cl"><span class="w"></span><span class="p">}</span><span class="w">
+</span></span></span><span class="line"><span class="cl"><span class="w">
+</span></span></span><span class="line"><span class="cl"><span class="w"></span><span class="c1">// 03. Customize names with the `as` keyword
+</span></span></span><span class="line"><span class="cl"><span class="c1"></span><span class="k">use</span><span class="w"> </span><span class="n">phrases</span>::<span class="n">greetings</span>::<span class="n">hello</span><span class="w"> </span><span class="k">as</span><span class="w"> </span><span class="n">greet</span><span class="p">;</span><span class="w">
+</span></span></span><span class="line"><span class="cl"><span class="w"></span><span class="k">fn</span> <span class="nf">main</span><span class="p">()</span><span class="w"> </span><span class="p">{</span><span class="w">
+</span></span></span><span class="line"><span class="cl"><span class="w"> </span><span class="n">greet</span><span class="p">();</span><span class="w">
+</span></span></span><span class="line"><span class="cl"><span class="w"></span><span class="p">}</span><span class="w">
+</span></span></span></code></pre></div><h2 id="02-import-elements-to-scope">02. Import elements to scope</h2>
+<p>Another common usage of <code>use</code> is importing elements to scope. Remember that, this is also a bit similar to creating an alias and using it instead of using the full path.</p>Variable bindings, Constants & Staticshttps://learning-rust.github.io/docs/variable-bindings-constants-and-statics/Mon, 01 Jan 0001 00:00:00 +0000https://learning-rust.github.io/docs/variable-bindings-constants-and-statics/<h2 id="variable-bindings-constants--statics">Variable bindings, Constants & Statics</h2>
+<p>βοΈ In Rust, variables are <strong>immutable by default</strong>, so we call them <strong>Variable bindings</strong>. To make them mutable, the <code>mut</code> keyword is used.</p>
+<p>βοΈ Rust is a <strong>statically typed</strong> language; it checks data types at compile-time. But it <strong>doesnβt require you to actually type it when declaring variable bindings</strong>. In that case, the compiler checks the usage and sets a better data type for it. But for <strong>constants and statics, you must annotate the type</strong>. Types come after a colon(<code>:</code>).</p>Vectorshttps://learning-rust.github.io/docs/vectors/Mon, 01 Jan 0001 00:00:00 +0000https://learning-rust.github.io/docs/vectors/<p>If you remember, the array is a fixed-size list of elements, of the same data type. Even with mut, its element count cannot be changed. A vector is kind of <strong>a re-sizable array</strong> but <strong>all elements must be in the same type</strong>.</p>
+<p>βοΈ Itβs a generic type, written as <strong><code>Vec<T></code></strong>Β . T can have any type, ex. The type of a Vec of i32s is <code>Vec<i32></code>. Also, Vectors always allocate their data in a dynamically allocated heap.</p>Why Rust?https://learning-rust.github.io/docs/why-rust/Mon, 01 Jan 0001 00:00:00 +0000https://learning-rust.github.io/docs/why-rust/<h2 id="history-of-rust">History of Rust</h2>
+<p>Rust was initially designed and developed by former Mozilla employee <strong><a href="https://github.com/graydon" target="_blank" >Graydon Hoare</a></strong> as a personal project. Mozilla began sponsoring the project in 2009 and announced it in 2010. But the first stable release, Rust 1.0, was released on May 15, 2015.</p>
+<p>Since Rust 1.0, major updates have been released as <a href="https://learning-rust.github.io/docs/cargo-crates-and-basic-project-structure/#rust-editions" ><code>Editions</code></a> approximately every three years: Rust 2015 (with the release of Rust 1.0) , Rust 2018, Rust 2021, and Rust 2024, all maintaining backward compatibility.</p>Workspaceshttps://learning-rust.github.io/docs/workspaces/Mon, 01 Jan 0001 00:00:00 +0000https://learning-rust.github.io/docs/workspaces/<p>When the code base is getting larger, you might need to work with <strong>multiple crates on the same project</strong>. Rust supports this via Workspaces. You can <strong>analyze (<code>cargo check</code>), build, run tests or generate docs for all crates</strong> at once by running <code>cargo</code> commands from the project root.</p>
+<p>βοΈ When working on multiple crates same time, there is a higher possibility of having shared dependencies on crates. To prevent downloading and compiling the same dependency multiple times, Rust uses a <strong>shared build directory</strong> under the project root, while running <code>cargo build</code> from the project root.</p>
\ No newline at end of file
diff --git a/docs/docs/installation/index.html b/docs/docs/installation/index.html
new file mode 100644
index 0000000..ea90f9e
--- /dev/null
+++ b/docs/docs/installation/index.html
@@ -0,0 +1,6 @@
+Installation Β· Learning Rust
+
There are many ways to install Rust on your system. For the moment the official way to install Rust is using Rustup.
π Rustup installs The Rust Programming Language from the official release channels, enabling you to easily switch between stable, beta, and nightly compilers and keep them updated. It also makes cross-compiling simpler with binary builds of the standard library for common platforms.
π Rustup installs rustc, cargo, rustup and other standard tools to Cargo’s bin directory. On Unix it is located at $HOME/.cargo/bin and on Windows at %USERPROFILE%\.cargo\bin. This is the same directory that cargo install will install Rust programs and Cargo plugins.
π The main tools Rustup installs to the Cargo’s bin directory,
rustc: The Rust compiler.
cargo: The Rustβs built-in package manager and the build system.
rustup: The Rust toolchain installer.
rustfmt: The Rustβs official tool of formatting Rust code according to style guidelines.
cargo-fmt: Helps to run rustfmt on whole Rust projects, including multi-crate workspaces.
cargo-clippy: A lint tool that provides extra checks for common mistakes and stylistic choices.
cargo-miri:An experimental Rust interpreter, which can be used for checking for undefined-behavior.
rustdoc: A local copy of the Rust documentation.
rust-analyzer: A language server that provides support for editors and IDEs.
rust-gdb: A debugger that wraps GNU Debugger(GDB).
Installation
For Mac and Linux Users
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh
+
For Windows Users
Download rustup-init.exe from www.rustup.rs and run.
π‘ You may need to install Visual C++ Build Tools 2019 or higher, which requires an additional 3β4 GBs.
π¨βπ« Before going to the next…
To verify the current Rust version, use the rustc --version or shorter formrustc -V command.
Rust follows six week release cycles. Use the rustup update command to update the Rust ecosystem.
You can access Rust’s offline documentation via the rustup doc command.
For a full list of rustup commands, refer to the rustup --help command.
\ No newline at end of file
diff --git a/docs/docs/learning_rust_medium.png b/docs/docs/learning_rust_medium.png
new file mode 100644
index 0000000..f2e7a46
Binary files /dev/null and b/docs/docs/learning_rust_medium.png differ
diff --git a/docs/docs/lifetimes/index.html b/docs/docs/lifetimes/index.html
new file mode 100644
index 0000000..a14f294
--- /dev/null
+++ b/docs/docs/lifetimes/index.html
@@ -0,0 +1,157 @@
+Lifetimes Β· Learning Rust
+
When we are dealing with references, we have to make sure that the referencing data stay alive until we stop using the references.
Think,
We have a variable binding, a.
We are referencing the value of a, from another variable bindingx.
+We have to make sure that a lives until we stop using x.
π Memory management is a form of resource management applied to computer memory. Up until the mid-1990s, the majority of programming languages used Manual Memory Management which requires the programmer to give manual instructions to identify and deallocate unused objects/ garbage. Around 1959 John McCarthy invented Garbage collection(GC), a form of Automatic Memory Management(AMM). It determines what memory is no longer used and frees it automatically instead of relying on the programmer. However Objective-C and Swift provide similar functionality through Automatic Reference Counting(ARC).
What is Lifetime?
In Rust,
A resource can only have one owner at a time. When it goes out of the scope, Rust removes it from the Memory.
When we want to reuse the same resource, we are referencing it/ borrowing its content.
When dealing with references, we have to specify lifetime annotations to provide instructions for the compiler to set how long those referenced resources should be alive.
β But because of lifetime annotations make the code more verbose, in order to make common patterns more ergonomic, Rust allows lifetimes to be elided/omitted in fn definitions. In this case, the compiler assigns lifetime annotations implicitly.
Lifetime annotations are checked at compile-time. Compiler checks when a data is used for the first and the last times. According to that, Rust manages memory in run time. This is the major reason for slower compilation times in Rust.
Unlike C and C++, usually, Rust doesnβt explicitly drop values at all.
Unlike GC, Rust doesnβt place deallocation calls where the data is no longer referenced.
Rust places deallocation calls where the data is about to go out of the scope and then enforces that no references to that resource exist after that point.
Usage
Lifetimes are denoted with an apostrophe. By convention, a lowercase letter is used for naming. Usually starts with'a and follows alphabetic order when we need to add multiple lifetime annotations.
When using references,
01. On Function Declaration
Input and output parameters with references should attach lifetimes after the & sign.
+ex. ..(x: &'a str) , ..(x: &'a mut str)
After the function name, we should mention that the given lifetimes are generic types.
+ex. fn foo<'a>(..) , fn foo<'a, 'b>(..)
// No inputs, return a reference
+fnfunction<'a>()-> &'astr{}
+
+// Single input
+fnfunction<'a>(x: &'astr){}
+
+// Single input and output, both have the same lifetime
+// The output should live at least as long as input exists
+fnfunction<'a>(x: &'astr)-> &'astr{}
+
+// Multiple inputs, only one input and the output share same lifetime
+// The output should live at least as long as y exists
+fnfunction<'a>(x: i32,y: &'astr)-> &'astr{}
+
+// Multiple inputs, both inputs and the output share same lifetime
+// The output should live at least as long as x and y exist
+fnfunction<'a>(x: &'astr,y: &'astr)-> &'astr{}
+
+// Multiple inputs, inputs can have different lifetimes π
+// The output should live at least as long as x exists
+fnfunction<'a,'b>(x: &'astr,y: &'bstr)-> &'astr{}
+
02. On Struct or Enum Declaration
Elements with references should attach lifetimes after the & sign.
After the name of the struct or enum, we should mention that the given lifetimes are generic types.
// Single element
+// Data of x should live at least as long as Struct exists
+structStruct<'a>{
+x: &'astr
+}
+
+// Multiple elements
+// Data of x and y should live at least as long as Struct exists
+structStruct<'a>{
+x: &'astr,
+y: &'astr
+}
+
+
+// Variant with a single element
+// Data of the variant should live at least as long as Enum exists
+enumEnum<'a>{
+Variant(&'aType)
+}
+
03. With Impls and Traits
structStruct<'a>{
+x: &'astr
+}
+impl<'a>Struct<'a>{
+fnfunction<'a>(&self)-> &'astr{
+self.x
+}
+}
+
+
+structStruct<'a>{
+x: &'astr,
+y: &'astr
+}
+impl<'a>Struct<'a>{
+fnnew(x: &'astr,y: &'astr)-> Struct<'a>{// No need to specify <'a> after new; impl already has it
+Struct{
+x: x,
+y: y
+}
+}
+}
+
+
+// π
+impl<'a>Trait<'a>forType
+impl<'a>TraitforType<'a>
+
As I mentioned earlier, in order to make common patterns more ergonomic, Rust allows lifetimes to be elided/omitted. This process is called Lifetime Elision.
π‘ For the moment Rust supports Lifetime Elisions only on fn definitions. But in the future, it will support for impl headers as well.
Lifetime annotations of fn definitions can be elided if its parameter list has either,
only one input parameter passes by reference.
a parameter with either&selfor&mut self reference.
fntriple(x: &u64)-> u64{// Only one input parameter passes by reference
+x*3
+}
+
+
+fnfilter(x: u8,y: &str)-> &str{// Only one input parameter passes by reference
+ifx>5{y}else{"invalid inputs"}
+}
+
+
+structPlayer<'a>{
+id: u8,
+name: &'astr
+}
+impl<'a>Player<'a>{// So far Lifetime Elisions are allowed only on fn definitions. But in the future, they might support on impl headers as well.
+fnnew(id: u8,name: &str)-> Player{// Only one input parameter passes by reference
+Player{
+id: id,
+name: name
+}
+}
+
+fnheading_text(&self)-> String{// An fn definition with &self (or &mut self) reference
+format!("{}: {}",self.id,self.name)
+}
+}
+
+fnmain(){
+letplayer1=Player::new(1,"Serena Williams");
+letplayer1_heading_text=player1.heading_text()
+println!("{}",player1_heading_text);
+}
+
π‘ In the Lifetime Elision process of fn definitions,
Each parameter passed by reference has got a distinct lifetime annotation.
+ex. ..(x: &str, y: &str) β ..<'a, 'b>(x: &'a str, y: &'b str)
If the parameter list only has one parameter passed by reference, that lifetime is assigned to all elided lifetimes in the return values of that function.
+ex. ..(x: i32, y: &str) -> &str β ..<'a>(x: i32, y: &'a str) -> &'a str
Even if it has multiple parameters passed by reference, if one of them has &self or &mut self, the lifetime of self is assigned to all elided output lifetimes.
+ex. impl Impl{ fn function(&self, x: &str) -> &str {} } β
+impl<'a> Impl<'a>{ fn function(&'a self, x: &'b str) -> &'a str {} }
For all other cases, we have to write lifetime annotations manually.
'static Annotations
'static lifetime annotation is a reserved lifetime annotation. These references are valid for the entire program. They are saved in the data segment of the binary and the data referred to will never go out of scope.
staticN: i32=5;// A constant with 'static lifetime
+
+leta="Hello, world.";// a: &'static str
+
+
+fnindex()-> &'staticstr{// No need to mention <'static> ; fn index ΜΆ<ΜΆ'ΜΆsΜΆtΜΆaΜΆtΜΆiΜΆcΜΆ>ΜΆ
+"Hello, world!"
+}
+
Few more examples about the usage of Rust lifetimes.
fngreeting<'a>()-> &'astr{
+"Hi!"
+}
+
+
+fnfullname<'a>(fname: &'astr,lname: &'astr)-> String{
+format!("{}{}",fname,lname)
+}
+
+
+structPerson<'a>{
+fname: &'astr,
+lname: &'astr
+}
+impl<'a>Person<'a>{
+fnnew(fname: &'astr,lname: &'astr)-> Person<'a>{// No need to specify <'a> after new; impl already has it
+Person{
+fname: fname,
+lname: lname
+}
+}
+
+fnfullname(&self)-> String{
+format!("{}{}",self.fname,self.lname)
+}
+}
+
+fnmain(){
+letplayer=Person::new("Serena","Williams");
+letplayer_fullname=player.fullname();
+
+println!("Player: {}",player_fullname);
+}
+
\ No newline at end of file
diff --git a/docs/docs/modules/index.html b/docs/docs/modules/index.html
new file mode 100644
index 0000000..6a18e65
--- /dev/null
+++ b/docs/docs/modules/index.html
@@ -0,0 +1,180 @@
+Modules Β· Learning Rust
+
Related code and data are grouped into a module and stored in the same file.
fnmain(){
+greetings::hello();
+}
+
+modgreetings{
+// βοΈ By default, everything inside a module is private
+pubfnhello(){// βοΈ So function has to be public to access from outside
+println!("Hello, world!");
+}
+}
+
Private functions can be called from the same module or from a child module.
// 01. Calling private functions of the same module
+fnmain(){
+phrases::greet();
+}
+
+modphrases{
+pubfngreet(){
+hello();// Or `self::hello();`
+}
+
+fnhello(){
+println!("Hello, world!");
+}
+}
+
+// 02. Calling private functions of the parent module
+fnmain(){
+phrases::greetings::hello();
+}
+
+modphrases{
+fnprivate_fn(){
+println!("Hello, world!");
+}
+
+pubmodgreetings{
+pubfnhello(){
+super::private_fn();
+}
+}
+}
+
π‘ The self keyword is used to refer the same module, while the super keyword is used to refer parent module. Also, the super keyword can be used to access root functions from inside a module.
π When writing tests itβs a good practice to write tests inside a test module because they compile only when running tests.
fngreet()-> String{
+"Hello, world!".to_string()
+}
+
+#[cfg(test)]// Only compiles when running tests
+modtests{
+usesuper::greet;// Import root greet function
+
+#[test]
+fntest_greet(){
+assert_eq!("Hello, world!",greet());
+}
+}
+
02. In a different file, same directory
// β³ main.rs
+modgreetings;// Import greetings module
+
+fnmain(){
+greetings::hello();
+}
+
+// β³ greetings.rs
+// βοΈ No need to wrap the code with a mod declaration. The file itself acts as a module.
+pubfnhello(){// The function has to be public to access from outside
+println!("Hello, world!");
+}
+
If we wrap file content with a mod declaration, it will act as a nested module.
// β³ main.rs
+modphrases;
+
+fnmain(){
+phrases::greetings::hello();
+}
+
+// β³ phrases.rs
+pubmodgreetings{// βοΈ The module has to be public to access from outside
+pubfnhello(){
+println!("Hello, world!");
+}
+}
+
03. In a different file, different directory
mod.rs in the directory module root is the entry point to the directory module. All other files in that directory root, act as sub-modules of the directory module.
// β³ main.rs
+modgreetings;
+
+fnmain(){
+greetings::hello();
+}
+
+// β³ greetings/mod.rs
+pubfnhello(){// βοΈ The function has to be public to access from outside
+println!("Hello, world!");
+}
+
Again, If we wrap file content with a mod declaration, it will act as a nested module.
// β³ main.rs
+modphrases;
+
+fnmain(){
+phrases::greetings::hello();
+}
+
+// β³ phrases/mod.rs
+pubmodgreetings{// βοΈ The module has to be public to access from outside
+pubfnhello(){
+println!("Hello, world!");
+}
+}
+
Other files in the directory module act as sub-modules for mod.rs.
π Itβs unable to import child file modules of directory modules to main.rs, so you canβt use mod phrases::greetings; from main.rs. But there is a way to import phrases::greetings::hello() to phrases module by re-exporting hello to phrases module. So you can call it directly as phrases::hello().
// β³ phrases/greetings.rs
+pubfnhello(){
+println!("Hello, world!");
+}
+
+// β³ phrases/mod.rs
+pubmodgreetings;
+
+pubuseself::greetings::hello;// Re-export `greetings::hello` to phrases
+
+// β³ main.rs
+modphrases;
+
+fnmain(){
+phrases::hello();// You can call `hello()` directly from phrases
+}
+
This allows you to present an external interface that may not directly map to your internal code organization. If still it is not clear, donβt worry; We discuss the usages of use on an upcoming section in this post.
\ No newline at end of file
diff --git a/docs/docs/operators/index.html b/docs/docs/operators/index.html
new file mode 100644
index 0000000..f40bdfe
--- /dev/null
+++ b/docs/docs/operators/index.html
@@ -0,0 +1,70 @@
+Operators Β· Learning Rust
+
leta=1;
+letb=2;
+
+letc=a&b;//0 (01 && 10 -> 00)
+letd=a|b;//3 (01 || 10 -> 11)
+lete=a^b;//3 (01 != 10 -> 11)
+letf=a<<b;//4 (Add b number of 0s to the end of a -> '01'+'00' -> 100)
+letg=a>>b;//0 (Remove b number of bits from the end of a -> oΜΆ1ΜΆ -> 0)
+
Assignment and Compound Assignment Operators
The = operator is used to assign a name to a value or a function. Compound Assignment Operators are created by composing one of + - * / % & | ^ << >> operators with = operator.
π The & or &mut operators are used for borrowing and * operator for dereferencing. For more information, refer Ownership, Borrowing & Lifetimes sections.
\ No newline at end of file
diff --git a/docs/docs/option-and-result/index.html b/docs/docs/option-and-result/index.html
new file mode 100644
index 0000000..0282dc5
--- /dev/null
+++ b/docs/docs/option-and-result/index.html
@@ -0,0 +1,87 @@
+Option and Result Β· Learning Rust
+
Many languages use null\ nil\ undefined types to represent empty outputs, and Exceptions to handle errors. Rust skips using both, especially to prevent issues like null pointer exceptions, sensitive data leakages through exceptions, etc. Instead, Rust provides two special generic enums;Option and Result to deal with above cases.
An optional value can have either Some value or no value/ None.
A result can represent either success/ Ok or failure/ Err
// An output can have either Some value or no value/ None.
+enumOption<T>{// T is a generic and it can contain any type of value.
+Some(T),
+None,
+}
+
+// A result can represent either success/ Ok or failure/ Err.
+enumResult<T,E>{// T and E are generics. T can contain any type of value, E can be any error.
+Ok(T),
+Err(E),
+}
+
π Also as we discussed in preludes, not only Option and Result, and also their variants are in preludes. So, we can use them directly without using namespaces in the code.
Basic usages of Option
When writing a function or data type,
if an argument of the function is optional,
if the function is non-void and if the output it returns can be empty,
if the value of a property of the data type can be empty,
we have to use their data type as an Option type.
For example, if the function outputs a &str value and the output can be empty, the return type of the function should be set as Option<&str>.
fnget_an_optional_value()-> Option<&str>{
+
+//if the optional value is not empty
+returnSome("Some value");
+
+//else
+None
+}
+
In the same way, if the value of a property of a data type can be empty or optional like the middle_name of the Name data type in the following example, we should set its data type as an Option type.
structName{
+first_name: String,
+middle_name: Option<String>,// middle_name can be empty
+last_name: String,
+}
+
π As you know, we can use pattern matching to catch the relevant return type (Some/ None) via match. There is a function in std::env called home_dir() to get the current user’s home directory. However, not all users have a home directory in systems like Linux, so the home directory of a user can be optional. So it returns an Option type; Option<PathBuf>.
usestd::env;
+
+fnmain(){
+lethome_path=env::home_dir();
+matchhome_path{
+Some(p)=>println!("{:?}",p),// This prints "/root", if you run this in Rust playground
+None=>println!("Can not find the home directory!"),
+}
+}
+
β However, when using optional arguments with functions, we have to pass None values for empty arguments while calling the function.
fnget_full_name(fname: &str,lname: &str,mname: Option<&str>)-> String{// middle name can be empty
+matchmname{
+Some(n)=>format!("{}{}{}",fname,n,lname),
+None=>format!("{}{}",fname,lname),
+}
+}
+
+fnmain(){
+println!("{}",get_full_name("Galileo","Galilei",None));
+println!("{}",get_full_name("Leonardo","Vinci",Some("Da")));
+}
+
+// π‘ Better create a struct as Person with fname, lname, mname fields and create a impl function as full_name()
+
π Other than that, Option types are used with nullable pointers in Rust. Because there are no null pointers in Rust, the pointer types should point to a valid location. So if a pointer can be nullable, we have use Option<Box<T>>Β .
Basic usages of Result
If a function can produce an error, we have to use a Result type by combining the data type of the valid output and the data type of the error. For example, if the data type of the valid output is u64 and error type is String, the return type should be Result<u64, String>.
π As you know, we can use the pattern matching to catch the relevant return types (Ok/Err) via match. There is a function to fetch the value of any environment variable in std::env called var(). Its input is the environment variable name. This can produce an error if we pass a wrong environment variable or the program cannot extract the value of the environment variable while running. So, its return type is a Result type; Result<String, VarError>.
usestd::env;
+
+fnmain(){
+letkey="HOME";
+matchenv::var(key){
+Ok(v)=>println!("{}",v),// This prints "/root", if you run this in Rust playground
+Err(e)=>println!("{}",e),// This prints "environment variable not found", if you give a nonexistent environment variable
+}
+}
+
is_some(), is_none(), is_ok(), is_err()
Other than match expressions, Rust provides is_some() , is_none() and is_ok() , is_err() functions to identify the return type.
\ No newline at end of file
diff --git a/docs/docs/overview/index.html b/docs/docs/overview/index.html
new file mode 100644
index 0000000..e01c571
--- /dev/null
+++ b/docs/docs/overview/index.html
@@ -0,0 +1,7 @@
+Overview Β· Learning Rust
+
π§βπ» I am an expat working in Singapore as a Go Backend and DevOps Engineer. Feel free to reach out if you find any mistakes or anything that needs to be changed, including spelling or grammar errors. Alternatively, you can create a pull request, open an issue, or share your awesome ideas in this gist. Good luck with learning Rust!
\ No newline at end of file
diff --git a/docs/docs/ownership/index.html b/docs/docs/ownership/index.html
new file mode 100644
index 0000000..18745fe
--- /dev/null
+++ b/docs/docs/ownership/index.html
@@ -0,0 +1,16 @@
+Ownership Β· Learning Rust
+
fnmain(){
+leta=[1,2,3];
+letb=a;
+println!("{:?}{:?}",a,b);// [1, 2, 3] [1, 2, 3]
+}
+
+fnmain(){
+leta=vec![1,2,3];
+letb=a;
+println!("{:?}{:?}",a,b);// Error; use of moved value: `a`
+}
+
In the above examples, we are just trying to assign the value of a to b . Almost the same code in both code blocks, but having two different data types. And the second one gives an error. This is because of the Ownership.
What is ownership?
βοΈ Variable bindings have ownership of what theyβre bound to. A piece of data can only have one owner at a time. When a binding goes out of scope, Rust will free the bound resources. This is how Rust achieves memory safety.
Ownership (noun) The act, state, or right of possessing something.
Copy types & move types
βοΈ When assigning a variable binding to another variable binding or when passing it to a function(Without referencing), if its data type is a
Copy Type
Bound resources are made a copy and assign or pass it to the function.
The ownership state of the original bindings is set to βcopiedβ state.
Mostly Primitive types
Move type
Bound resources are moved to the new variable binding and we can not access the original variable binding anymore.
The ownership state of the original bindings is set to βmovedβ state.
Non-primitive types
π The functionality of a type is handled by the traits which have been implemented to it. By default, variable bindings have βmove semantics.β However, if a type implements core::marker::Copy trait , it has a ‘copy semantics’.
π‘ So in the above second example, ownership of the Vec object moves to b and a doesnβt have any ownership to access the resource.
\ No newline at end of file
diff --git a/docs/docs/panicking/index.html b/docs/docs/panicking/index.html
new file mode 100644
index 0000000..b95d6bf
--- /dev/null
+++ b/docs/docs/panicking/index.html
@@ -0,0 +1,147 @@
+Panicking Β· Learning Rust
+
In some cases, when an error occurs we can not do anything to handle it, if the error is something which should not have happened. In other words, if itβs an unrecoverable error.
Also when we are not using a feature-rich debugger or proper logs, sometimes we need to debug the code by quitting the program from a specific line of code by printing out a specific message or a value of a variable binding to understand the current flow of the program.
+For above cases, we can use panic! macro.
β panic!() runs thread based. One thread can be panicked, while other threads are running.
01. Quit from a specific line.
fnmain(){
+// some code
+
+// if we need to debug in here
+panic!();
+}
+
+// -------------- Compile-time error --------------
+thread'main'panickedat'explicitpanic',src/main.rs:5:5
+
02. Quit with a custom error message.
#[allow(unused_mut)]// π‘ A lint attribute used to suppress the warning; username variable does not need to be mutable
+fnmain(){
+letmutusername=String::new();
+
+// some code to get the name
+
+ifusername.is_empty(){
+panic!("Username is empty!");
+}
+
+println!("{}",username);
+}
+
+// -------------- Compile-time error --------------
+thread'main'panickedat'Usernameisempty!',src/main.rs:8:9
+
03. Quit with the value of code elements.
#[derive(Debug)]// π‘ A lint attribute which use to implement `std::fmt::Debug` to Color
+structColor{
+r: u8,
+g: u8,
+b: u8,
+}
+
+#[allow(unreachable_code)]// π‘ A lint attribute used to suppress the warning; unreachable statement
+fnmain(){
+letsome_color: Color;
+
+// some code to get the color. ex
+some_color=Color{r: 255,g: 255,b: 0};
+
+// if we need to debug in here
+panic!("{:?}",some_color);
+
+println!(
+"The color = rgb({},{},{})",
+some_color.r,some_color.g,some_color.b
+);
+}
+
+// -------------- Compile-time error --------------
+thread'main'panickedat'Color{r: 255,g: 255,b: 0}',src/main.rs:16:5
+
As you can see in the above examples panic!() supports println!() type style arguments. By default, it prints the error message, file path and line & column numbers where the error happens.
unimplemented!()
π‘ If your code is having unfinished code sections, there is a standardized macro as unimplemented!() to mark those routes. The program will be panicked with a βnot yet implementedβ error message, if the program runs through those routes.
This is the standard macro to mark routes that the program should not enter. The program will be panicked with a β‘internal error: entered unreachable code’β error message, if the program entered those routes.
π These are similar to above assert macros. But these statements are only enabled in non optimized builds by default. All these debug_assert macros will be omitted in release builds, unless we pass -C debug-assertions to the compiler.
\ No newline at end of file
diff --git a/docs/docs/primitive-data-types/index.html b/docs/docs/primitive-data-types/index.html
new file mode 100644
index 0000000..2b5bd74
--- /dev/null
+++ b/docs/docs/primitive-data-types/index.html
@@ -0,0 +1,91 @@
+Primitive Data Types Β· Learning Rust
+
letx='x';
+lety: char='π';
+
+// βοΈ no "x", only single quotes
+
Because of Unicode support, char is not a single byte, but four(32 bits).
i8, i16, i32, i64, i128
8, 16, 32, 64 and 128 bit fixed sized signed(+/-) integer types
DATA TYPE
MIN
MAX
i8
-128
127
i16
-32768
32767
i32
-2147483648
2147483647
i64
-9223372036854775808
9223372036854775807
i128
-170141183460469231731687303715884105728
170141183460469231731687303715884105727
π‘ The min and max values are based on the following equation; from -(2βΏβ»ΒΉ) to 2βΏβ»ΒΉ-1. You can use min_value() and max_value() functions to find min and max of each integer type. ex.i8::min_value();
letx=10;// βοΈ The default integer type in Rust is i32
+lety: i8=-128;
+
u8, u16, u32, u64, u128
8, 16, 32, 64 and 128 bit fixed sized unsigned(0/+) integer types
DATA TYPE
MIN
MAX
u8
0
255
u16
0
65535
u32
0
4294967295
u64
0
18446744073709551615
u128
0
340282366920938463463374607431768211455
π‘ The min and max values are based on the following equation; from 0 to 2βΏ-1. Same way you can use min_value() and max_value() functions to find min and max of each integer type. ex.u8::max_value();
isize, usize
Pointer sized signed and unsigned integer types
The actual bit size depends on the computer architecture you are compiling your program for. By default, the sizes are equal to 32 bits on 32-bit platforms and 64 bits on 64-bit platforms.
32 and 64 bit sized floating point numbers(numbers with decimal points)
Rust follows IEEE Standard for Binary Floating-Point Arithmetic. The f32 type is similar to float(Single precision) in other languages, while f64 is similar to double(Double precision) in other languages.
letx=1.5;// βοΈ The default float type in Rust is f64
+lety: f64=2.0;
+
π‘ Should avoid using f32, unless you need to reduce memory consumption badly or if you are doing low-level optimization, when targeted hardware does not support for double-precision or when single-precision is faster than double-precision on it.
βοΈ Arrays are immutable by default and even with mut, its element count cannot be changed.
π If you are looking for a dynamic/ growable array, you can use vectors. Vectors can contain any type of elements but all elements must be in the same data type.
Tuple
Fixed size ordered list of elements of different(or same) data types
βοΈ Tuples are also immutable by default and even with mut, its element count cannot be changed. Also, if you want to change an elementβs value, the new value should have the same data type of previous value.
Slice
Dynamically-sized reference to another data structure
Imagine you want to get/ pass a part of an array or any other data structure. Instead of copying it to another array (or same data structure), Rust allows for creating a view/ reference to access only that part of the data. This view/ reference can be mutable or immutable.
leta: [i32;4]=[1,2,3,4];// Parent Array
+
+letb: &[i32]=&a;// Slicing whole array
+letc=&a[0..4];// From 0th position to 4th(excluding)
+letd=&a[..];// Slicing whole array
+
+lete=&a[1..3];// [2, 3]
+letf=&a[1..];// [2, 3, 4]
+letg=&a[..3];// [1, 2, 3]
+
βοΈ It’s an immutable/ statically allocated slice holding an unknown sized sequence of UTF-8 code points stored in somewhere in memory. &str is used to borrow and assign the whole array to the given variable binding.
In Rust, the default integer type is i32 and the default float type is f64.
leti=10;// Equals to `let i: i32 = 10;`
+letf=3.14;// Equals to `let f: f64 = 3.14;`
+
Other than adding the type annotations to the variables, for numeric types, we can append the data type directly to the value as the suffix. Also, to improve the readability of long numbers, we can use _ as a divider.
leta=5i8;// Equals to `let a: i8 = 5;`
+
+letb=100_000_000;// Equals to `let b = 100000000;`
+// π‘ The placements of _s are not strict. ex. 10000_0000 is also valid.
+
+letpi=3.141_592_653_59f64;// Equals to `let pi: f64 = 3.14159265359`
+
+constPI: f64=3.141_592_653_59;// In the constants and statics, the data type must be annotated in the beginning.
+
There are several string types in Rust. The String type is a heap-allocated string. This string is growable and is also guaranteed to be UTF-8. In general, you should use String when you need ownership, and &str when you just need to borrow a string.
A String type can be generated from a &str type, via the to_string() or String::from() methods. With as_str() method, a String type can be converted to a &str type.
The Rust compiler does the most significant job to prevent errors in Rust programs. It analyzes the code at compile-time and issues warnings, if the code does not follow memory management rules or lifetime annotations correctly.
For example,
#[allow(unused_variables)]//π‘ A lint attribute used to suppress the warning; unused variable: `b`
+fnmain(){
+leta=vec![1,2,3];
+letb=a;
+
+println!("{:?}",a);
+}
+
+
+// ------ Compile-time error ------
+error[E0382]: useofmovedvalue: `a`
+--> src/main.rs:6:22
+|
+3|letb=a;
+|-valuemovedhere
+4|
+5|println!("{:?}",a);
+|^valueusedhereaftermove
+|
+=note: moveoccursbecause`a`hastype`std::vec::Vec<i32>`,whichdoesnotimplementthe`Copy`trait
+
+error: abortingduetopreviouserror
+Formoreinformationaboutthiserror,try`rustc--explainE0382`.
+
+// β instead using #[allow(unused_variables)], consider using "let _b = a;" in line 4.
+// Also you can use "let _ =" to completely ignore return values
+
π In the previous sections, we have discussed memory management concepts like ownership, borrowing, lifetimes and etc.
Rust compiler checks not only issues related with lifetimes or memory management and also common coding mistakes, like the following code.
Above error messages are very descriptive and we can easily see where is the error. But while we can not identify the issue via the error message, rustc --explain commands help us to identify the error type and how to solve it, by showing simple code samples which express the same problem and the solution we have to use.
For example, rustc --explain E0571 shows the following output in the console.
A`break`statementwithanargumentappearedinanon-`loop`loop.
+
+Exampleoferroneouscode:
+ο½ο½ο½
+letresult=whiletrue{
+ifsatisfied(i){
+break2*i;// error: `break` with value from a `while` loop
+}
+i+=1;
+};
+ο½ο½ο½
+
+The`break`statementcantakeanargument(whichwillbethevalueoftheloop
+expressionifthe`break`statementisexecuted)in`loop`loops,butnot
+`for`,`while`,or`whilelet`loops.
+
+Makesure`breakvalue;`statementsonlyoccurin`loop`loops:
+ο½ο½ο½
+letresult=loop{// ok!
+ifsatisfied(i){
+break2*i;
+}
+i+=1;
+};
+ο½ο½ο½
+
\ No newline at end of file
diff --git a/docs/docs/std-primitives-and-preludes/index.html b/docs/docs/std-primitives-and-preludes/index.html
new file mode 100644
index 0000000..7ae4ba8
--- /dev/null
+++ b/docs/docs/std-primitives-and-preludes/index.html
@@ -0,0 +1,93 @@
+STD, Primitives and Preludes Β· Learning Rust
+
The std library has been divided into modules, according to the main areas each covered.
βοΈ While primitives are implemented by the compiler, the standard library implements the most useful methods directly on the primitive types. But some rarely useful language elements of some primitives are stored on relevant std modules. This is why you can see char, str and integer types on both primitives and std modules.
Primitives
// Primitives: Defined by the compiler and methods are directly implemented by std
+bool,char,slice,str
+
+i8,i16,i32,i64,i128,isize
+u8,u16,u32,u64,u128,usize
+
+f32,f64
+
+array,tuple
+
+pointer,fn,reference
+
Standard Macros
// Standard Macros also defined by both compiler and std
+print,println,eprint,eprintln
+format,format_args
+write,writeln
+
+concat,concat_idents,stringify// concat_idents: nightly-only experimental API
+
+include,include_bytes,include_str
+
+assert,assert_eq,assert_ne
+debug_assert,debug_assert_eq,debug_assert_ne
+
+try,panic,compile_error,unreachable,unimplemented
+
+file,line,column,module_path
+env,option_env
+cfg
+
+select,thread_local// select: nightly-only experimental API
+
+vec
+
π When examining Rustβs source code, you can see that the src directory is a workspace. Even though it is having many library crates, by examining root Cargo.toml file you can easily identify that main crates are rustc(compiler) and libstd (std). In libstd/lib.rs std modules have been re-exported via pub use and the original location of most of the std modules is src/libcore.
Few important std modules are,
std::io - Core I/O functionality
std::fs - Filesystem specific functionality
std::path - Cross-platform path specific functionality
std::env - Processβs environment related functionality
std::mem - Memory related functionality
std::net - TCP/UDP communication
std::os - OS specific functionality
std::thread - Native threads specific functionality
Even though Rust std contains many modules, by default it doesnβt load each and everything of std library on every rust program. Instead, it loads only the smallest list of things which require for almost every single Rust program. These are called preludes. They import only,
extern crate std; : into the crate root of every crate
use std::prelude::v1::*; : into every module
+So you donβt need to import these each time.
The concept of preludes is quite common on Rust libraries. Even some modules inside std crate (ex.std::io) and many libraries (ex. Diesel) are having their own prelude modules.
βοΈ But preludes are used to create a single place to import all important components which are required while using the library. They do not load automatically unless you imported them manually. Only std::prelude imports automatically in every Rust programs.
\ No newline at end of file
diff --git a/docs/docs/structs/index.html b/docs/docs/structs/index.html
new file mode 100644
index 0000000..6fab996
--- /dev/null
+++ b/docs/docs/structs/index.html
@@ -0,0 +1,66 @@
+Structs Β· Learning Rust
+
βοΈ Structs are used to encapsulate related properties into one unified data type.
π‘ By convention, the name of the struct should follow PascalCase.
There are 3 variants of structs,
C-like structs
One or more comma-separated name:value pairs
Brace-enclosed list
Similar to classes (without its methods) in OOP languages
Because fields have names, we can access them through dot notation
Tuple structs
One or more comma-separated values
A parenthesized list like tuples
Looks like a named tuples
Unit structs
A struct with no members at all
It defines a new type but it resembles an empty tuple, ()
Rarely in use, useful with generics
βοΈ When regarding OOP in Rust, attributes and methods are placed separately on structs and traits. Structs contain only attributes, traits contain only methods. They are getting connected via impls.
// Struct Declaration
+structColor{
+red: u8,
+green: u8,
+blue: u8
+}
+
+fnmain(){
+// Creating an instance
+letblack=Color{red: 0,green: 0,blue: 0};
+
+// Accessing its fields using dot notation
+println!("Black = rgb({}, {}, {})",black.red,black.green,black.blue);//Black = rgb(0, 0, 0)
+
+// Structs are immutable by default, use `mut` to make it mutable but doesn't support field level mutability
+letmutlink_color=Color{red: 0,green: 0,blue: 255};
+link_color.blue=238;
+println!("Link Color = rgb({}, {}, {})",link_color.red,link_color.green,link_color.blue);//Link Color = rgb(0, 0, 238)
+
+// Copy elements from another instance
+letblue=Color{blue: 255,..link_color};
+println!("Blue = rgb({}, {}, {})",blue.red,blue.green,blue.blue);//Blue = rgb(0, 0, 255)
+
+// Destructure the instance using a `let` binding, this will not destruct blue instance
+letColor{red: r,green: g,blue: b}=blue;
+println!("Blue = rgb({}, {}, {})",r,g,b);//Blue = rgb(0, 0, 255)
+
+// Creating an instance via functions & accessing its fields
+letmidnightblue=get_midnightblue_color();
+println!("Midnight Blue = rgb({}, {}, {})",midnightblue.red,midnightblue.green,midnightblue.blue);//Midnight Blue = rgb(25, 25, 112)
+
+// Destructure the instance using a `let` binding
+letColor{red: r,green: g,blue: b}=get_midnightblue_color();
+println!("Midnight Blue = rgb({}, {}, {})",r,g,b);//Midnight Blue = rgb(25, 25, 112)
+}
+
+fnget_midnightblue_color()-> Color{
+Color{red: 25,green: 25,blue: 112}
+}
+
Tuple structs
βοΈ When a tuple struct has only one element, we call it newtype pattern. Because it helps to create a new type.
structColor(u8,u8,u8);
+structKilometers(i32);
+
+fnmain(){
+// Creating an instance
+letblack=Color(0,0,0);
+
+// Destructure the instance using a `let` binding, this will not destruct black instance
+letColor(r,g,b)=black;
+println!("Black = rgb({}, {}, {})",r,g,b);//black = rgb(0, 0, 0);
+
+// Newtype pattern
+letdistance=Kilometers(20);
+// Destructure the instance using a `let` binding
+letKilometers(distance_in_km)=distance;
+println!("The distance: {} km",distance_in_km);//The distance: 20 km
+}
+
Unit structs
This is rarely useful on its own. But in combination with other features, it can become useful.
π ex: A library may ask you to create a structure that implements a certain trait to handle events. If you donβt have any data you need to store in the structure, you can create a unit-like struct.
structElectron;
+
+fnmain(){
+letx=Electron;
+}
+
\ No newline at end of file
diff --git a/docs/docs/unwrap-and-expect/index.html b/docs/docs/unwrap-and-expect/index.html
new file mode 100644
index 0000000..dca2ca0
--- /dev/null
+++ b/docs/docs/unwrap-and-expect/index.html
@@ -0,0 +1,162 @@
+Unwrap and Expect Β· Learning Rust
+
If an Option type has Some value or a Result type has a Ok value, the value inside them passes to the next step.
If the Option type has None value or the Result type has Err value, program panics; If Err, panics with the error message.
The functionality is bit similar to the following codes, which are using match instead unwrap().
Example with Option and match, before using unwrap()
fnmain(){
+letx;
+matchget_an_optional_value(){
+Some(v)=>x=v,// if Some("abc"), set x to "abc"
+None=>panic!(),// if None, panic without any message
+}
+
+println!("{}",x);// "abc" ; if you change line 14 `false` to `true`
+}
+
+fnget_an_optional_value()-> Option<&'staticstr>{
+
+//if the optional value is not empty
+iffalse{
+returnSome("abc");
+}
+
+//else
+None
+}
+
+
+// --------------- Compile-time error ---------------
+thread'main'panickedat'explicitpanic',src/main.rs:5:17
+
Example with Result and match, before using unwrap()
fnmain(){
+letx;
+matchfunction_with_error(){
+Ok(v)=>x=v,// if Ok(255), set x to 255
+Err(e)=>panic!(e),// if Err("some message"), panic with error message "some message"
+}
+
+println!("{}",x);// 255 ; if you change line 13 `true` to `false`
+}
+
+fnfunction_with_error()-> Result<u64,String>{
+//if error happens
+iftrue{
+returnErr("some message".to_string());
+}
+
+// else, return valid output
+Ok(255)
+}
+
+
+// ---------- Compile-time error ----------
+thread'main'panickedat'somemessage',src/main.rs:5:19
+
Same codes in above main functions can be written with unwrap() using two lines.
The opposite case of unwrap() and expect(); Panics with Ok values, instead Err. Both print the value inside Ok on the error message.
π‘ Usually use with tests.
// 01. unwrap_err error message for Ok
+fnmain(){
+leto: Result<i8,&str>=Ok(8);
+
+o.unwrap_err();
+}
+
+// ---------- Compile-time error ----------
+thread'main'panickedat'called`Result::unwrap_err()`onan`Ok`value: 8',libcore/result.rs:945:5
+
+
+// 02. expect_err error message for Ok
+fnmain(){
+leto: Result<i8,&str>=Ok(8);
+
+o.expect_err("Should not get Ok value");
+}
+
+// ---------- Compile-time error ----------
+thread'main'panickedat'ShouldnotgetOkvalue: 8',libcore/result.rs:945:5
+
unwrap_or(), unwrap_or_default() and unwrap_or_else()
π‘ These are bit similar to unwrap(), If an Option type has Some value or a Result type has a Ok value, the value inside them passes to the next step. But when having None or Err, the functionalities are bit different.
unwrap_or()Β : With None or Err, the value you passes to unwrap_or() is passing to the next step. But the data type of the value you passes should match with the data type of the relevant Some or Ok.
unwrap_or_default()Β : With None or Err, the default value of the data type of the relevant Some or Ok, is passing to the next step.
fnmain(){
+letv=8;
+letv_default=0;
+
+lets_v: Option<i8>=Some(8);
+letn: Option<i8>=None;
+
+assert_eq!(s_v.unwrap_or_default(),v);// Some(v) unwrap_or_default = v
+assert_eq!(n.unwrap_or_default(),v_default);// None unwrap_or_default = default value of v
+
+leto_v: Result<i8,&str>=Ok(8);
+lete: Result<i8,&str>=Err("error");
+
+assert_eq!(o_v.unwrap_or_default(),v);// Ok(v) unwrap_or_default = v
+assert_eq!(e.unwrap_or_default(),v_default);// Err unwrap_or_default = default value of v
+}
+
unwrap_or_else()Β : Similar to unwrap_or(). The only difference is, instead of passing a value, you have to pass a closure which returns a value with the same data type of the relevant Some or Ok.
\ No newline at end of file
diff --git a/docs/docs/use/index.html b/docs/docs/use/index.html
new file mode 100644
index 0000000..37f4352
--- /dev/null
+++ b/docs/docs/use/index.html
@@ -0,0 +1,95 @@
+Use Β· Learning Rust
+
Mainly use keyword is used to bind a full path of an element to a new name. So the user doesnβt want to repeat the full path each time.
// -- Initial code without the `use` keyword --
+modphrases{
+pubmodgreetings{
+pubfnhello(){
+println!("Hello, world!");
+}
+}
+}
+
+fnmain(){
+phrases::greetings::hello();// Using full path
+}
+
+
+// -- Usage of the `use` keyword --
+// 01. Create an alias for module
+usephrases::greetings;
+fnmain(){
+greetings::hello();
+}
+
+// 02. Create an alias for module elements
+usephrases::greetings::hello;
+fnmain(){
+hello();
+}
+
+// 03. Customize names with the `as` keyword
+usephrases::greetings::helloasgreet;
+fnmain(){
+greet();
+}
+
02. Import elements to scope
Another common usage of use is importing elements to scope. Remember that, this is also a bit similar to creating an alias and using it instead of using the full path.
fnhello()-> String{
+"Hello, world!".to_string()
+}
+
+#[cfg(test)]
+modtests{
+usesuper::hello;// Import the `hello()` function into the scope
+
+#[test]
+fntest_hello(){
+assert_eq!("Hello, world!",hello());// If not using the above `use` statement, we can run same via `super::hello()`
+}
+}
+
π‘ By default, use declarations use absolute paths, starting from the crate root. But self and super declarations make that path relative to the current module.
Same way the use keyword is used to import the elements of other crates including the std, Rustβs Standard Library.
// -- 01. Importing elements --
+usestd::fs::File;
+
+fnmain(){
+File::create("empty.txt").expect("Can not create the file!");
+}
+
+
+// -- 02. Importing module and elements --
+usestd::fs::{self,File}// `use std::fs; use std::fs::File;`
+
+fnmain(){
+fs::create_dir("some_dir").expect("Can not create the directry!");
+File::create("some_dir/empty.txt").expect("Can not create the file!");
+}
+
+
+// -- 03. Importing multiple elements --
+usestd::fs::File;
+usestd::io::{BufReader,BufRead};// `use std::io::BufReader; use std::io::BufRead;`
+
+fnmain(){
+letfile=File::open("src/hello.txt").expect("file not found");
+letbuf_reader=BufReader::new(file);
+
+forlineinbuf_reader.lines(){
+println!("{}",line.unwrap());
+}
+}
+
We donβt need to use extern crate std; when using the std library. We will discuss more about this under the Standard Library section.
π‘ use statements import only what weβve specified into the scope, instead of importing all elements of a module or crate. So it improves the efficiency of the program.
03. Re-exporting
Another special case is pub use. When creating a module, you can export things from another module into your module. So after that, they can be accessed directly from your module. This is called re-exporting.
This pattern is quite common in large libraries. It helps to hide the complexity of the internal module structure of the library from users. Because users donβt need to know/follow the whole directory map of the elements of the library while working with them.
\ No newline at end of file
diff --git a/docs/docs/variable-bindings-constants-and-statics/index.html b/docs/docs/variable-bindings-constants-and-statics/index.html
new file mode 100644
index 0000000..d2431a6
--- /dev/null
+++ b/docs/docs/variable-bindings-constants-and-statics/index.html
@@ -0,0 +1,43 @@
+Variable bindings, Constants & Statics Β· Learning Rust
+
βοΈ In Rust, variables are immutable by default, so we call them Variable bindings. To make them mutable, the mut keyword is used.
βοΈ Rust is a statically typed language; it checks data types at compile-time. But it doesnβt require you to actually type it when declaring variable bindings. In that case, the compiler checks the usage and sets a better data type for it. But for constants and statics, you must annotate the type. Types come after a colon(:).
π In the following examples, we will use data types like bool, i32, i64 and f64. Don’t worry about them for now; they’ll be discussed later.
Variable bindings
The let keyword is used in binding expressions. We can bind a name to a value or a function. Also, because the left-hand side of a let expression is a “pattern”, you can bind multiple names to a set of values or function values.
leta;// Declaration; without data type
+a=5;// Assignment
+
+letb: i8;// Declaration; with data type
+b=5;
+
+lett=true;// Declaration + assignment; without data type
+letf: bool=false;// Declaration + assignment; with data type
+
+let(x,y)=(1,2);// x = 1 and y = 2
+
+letmutz=5;
+z=6;
+
+letz={x+y};// z = 3
+
+letz={
+letx=1;
+lety=2;
+
+x+y
+};// z = 3
+
Constants
The const keyword is used to define constants and after the assignment their values are not allowed to change. They live for the entire lifetime of a program but has no fixed address in the memory.
constN: i32=5;
+
Statics
The static keyword is used to define a “global variable” type facility. There is only one instance for each value, and itβs at a fixed location in memory.
staticN: i32=5;
+
π While you need constants, always use const, instead of static. Itβs pretty rare that you actually want a memory location associated with your constant, and using a const allows for optimizations like constant propagation, not only in your crate but also in downstream crates.
Variable Shadowing
Sometimes, while dealing with data, initially we get them in one unit but need to transform them into another unit for further processing. In this situation, instead of using different variable names, Rust allows us to redeclare the same variable with a different data type and/ or with a different mutability setting. We call this Shadowing.
The naming convention for the variable bindings is using the snake_case. But, for constants and statics, we should follow the SCREAMING_SNAKE_CASE.
Usually, constants and statics are placed at the top of the code file, outside the functions (after module imports/ use declarations).
constPI: f64=3.14159265359;
+
+fnmain(){
+println!("Ο value is {}",PI);
+}
+
\ No newline at end of file
diff --git a/docs/docs/vectors/index.html b/docs/docs/vectors/index.html
new file mode 100644
index 0000000..6dc1b0f
--- /dev/null
+++ b/docs/docs/vectors/index.html
@@ -0,0 +1,52 @@
+Vectors Β· Learning Rust
+
If you remember, the array is a fixed-size list of elements, of the same data type. Even with mut, its element count cannot be changed. A vector is kind of a re-sizable array but all elements must be in the same type.
βοΈ Itβs a generic type, written as Vec<T>Β . T can have any type, ex. The type of a Vec of i32s is Vec<i32>. Also, Vectors always allocate their data in a dynamically allocated heap.
Create empty vector
letmuta=Vec::new();//1.With new() keyword
+letmutb=vec![];//2.Using the vec! macro
+
Create with data types
letmuta2: Vec<i32>=Vec::new();
+letmutb2: Vec<i32>=vec![];
+letmutb3=vec![1i32,2,3];//Suffixing 1st value with data type
+
+letmutb4=vec![1,2,3];
+letmutb5: Vec<i32>=vec![1,2,3];
+letmutb6=vec![1i32,2,3];
+letmutb7=vec![0;10];//Ten zeroes
+
Access and change data
//Accessing and changing existing data
+letmutc=vec![5,4,3,2,1];
+c[0]=1;
+c[1]=2;
+//c[6] = 2; Cannot assign values this way, index out of bounds
+println!("{:?}",c);//[1, 2, 3, 2, 1]
+
+//push and pop
+letmutd: Vec<i32>=Vec::new();
+d.push(1);//[1] : Add an element to the end
+d.push(2);//[1, 2]
+d.pop();//[1] : : Remove an element from the end
+
+
+// π Capacity and reallocation
+letmute: Vec<i32>=Vec::with_capacity(10);
+println!("Length: {}, Capacity : {}",e.len(),e.capacity());//Length: 0, Capacity : 10
+
+// These are all done without reallocating...
+foriin0..10{
+e.push(i);
+}
+// ...but this may make the vector reallocate
+e.push(11);
+
βοΈ Mainly a vector represent 3 things,
A pointer to the data
No of elements currently have(length)
Capacity (Amount of space allocated for any future elements).
If the length of a vector exceeds its capacity, its capacity will be increased automatically. But its elements will be reallocated(which can be slow). So always use Vec::with_capacity whenever itβs possible.
π‘ The String data type is a UTF-8 encoded vector. But you can not index into a String because of encoding.
π― Vectors can be used with iterators in three ways,
letmutv=vec![1,2,3,4,5];
+
+foriin&v{
+println!("A reference to {}",i);
+}
+
+foriin&mutv{
+println!("A mutable reference to {}",i);
+}
+
+foriinv{
+println!("Take ownership of the vector and its element {}",i);
+}
+
\ No newline at end of file
diff --git a/docs/docs/why-rust/index.html b/docs/docs/why-rust/index.html
new file mode 100644
index 0000000..59a8c3b
--- /dev/null
+++ b/docs/docs/why-rust/index.html
@@ -0,0 +1,5 @@
+Why Rust? Β· Learning Rust
+
Rust was initially designed and developed by former Mozilla employee Graydon Hoare as a personal project. Mozilla began sponsoring the project in 2009 and announced it in 2010. But the first stable release, Rust 1.0, was released on May 15, 2015.
Since Rust 1.0, major updates have been released as Editions approximately every three years: Rust 2015 (with the release of Rust 1.0) , Rust 2018, Rust 2021, and Rust 2024, all maintaining backward compatibility.
Initial Goals
The goal of Rust is to be a good programming language for creating highly concurrent, safe and performant systems.
“Rust is a systems programming language focused on three goals: safety, speed, and concurrency.”~ Rust Documentation
Rust is a very young and very modern language. It’s a compiled programming language and it uses LLVM on the backend. Also, Rust is a multi-paradigm programming language, which supports imperative procedural, concurrent actor, object-oriented and pure functional styles. It also supports generic programming and metaprogramming, in both static and dynamic styles.
One of Rustβs most unique and compelling features is Ownership, which is used to achieve memory safety. Rust creates memory pointers optimistically, checks memory pointersβ limited accesses at compile-time with the usage of References and Borrowing. And it does automatic compile-time memory management by checking the Lifetimes.
Influences
Its design elements came from a wide range of sources.
Abstract Machine Model: C
Data types: C, SML, OCaml, Lisp, Limbo
Optional Bindings: Swift
Hygienic Macros: Scheme
Functional Programming: Haskell, OCaml, F#
Attributes: ECMA-335
Memory Model and Memory Management: C++, ML Kit, Cyclone
Type Classes: Haskell
Crate: Assembly in the ECMA-335 CLI model
Channels and Concurrency: Newsqueak, Alef, Limbo
Message passing and Thread failure: Erlang
and etc.
Rust doesn’t use a built-in runtime or an automated garbage collection system (GC).
π‘ However, async Rust requires an async runtime, which is provided by community-maintained crates like tokio, async-std, soml etc. The async runtime will be bundled into the final executable.
Rust compiler observes the code at compile-time and helps to prevent many types of errors that are possible to write in C, C++ like programming languages.
π¨βπ« Before going to the next…
The following guides will be helpful for you to understand the maturity of the Rust ecosystem and the tools you need to choose, according to the area you want to master.
\ No newline at end of file
diff --git a/docs/docs/workspaces/index.html b/docs/docs/workspaces/index.html
new file mode 100644
index 0000000..718cfeb
--- /dev/null
+++ b/docs/docs/workspaces/index.html
@@ -0,0 +1,55 @@
+Workspaces Β· Learning Rust
+
When the code base is getting larger, you might need to work with multiple crates on the same project. Rust supports this via Workspaces. You can analyze (cargo check), build, run tests or generate docs for all crates at once by running cargo commands from the project root.
βοΈ When working on multiple crates same time, there is a higher possibility of having shared dependencies on crates. To prevent downloading and compiling the same dependency multiple times, Rust uses a shared build directory under the project root, while running cargo build from the project root.
Let’s create a library crate with a simple hello world function and a binary crate which uses the library crate.
Assume we run,
mkdir greetings
+touch greetings/Cargo.toml
+cargo new greetings/lib --lib
+cargo new greetings/examples/hello
+
// 01. greetings/Cargo.toml to mark as a workspace and to add members
+[workspace]
+members=[
+"lib",
+"examples/hello"
+]
+
+// 02.1 greetings/lib/Cargo.toml to change the package name to greetings
+[package]
+name="greetings"
+version="0.1.0"
+authors=["Dumindu Madunuwan"]
+
+[dependencies]
+
+// 02.2 greetings/lib/src/lib.rs to add a simple hello world function
+pubfnhello(){
+println!("Hello, world!");
+}
+
+// 03.1 greetings/examples/hello/Cargo.toml to add the `greetings` lib as a dependency
+[package]
+name="hello"
+version="0.1.0"
+authors=["Dumindu Madunuwan"]
+
+[dependencies]
+greetings={path="../../lib"}
+
+// 03.2 greetings/examples/hello/src/main.rs to import the `greetings` lib and call its hello world function
+externcrategreetings;
+
+fnmain(){
+greetings::hello();
+}
+
π‘ On Linux and Mac, you can run cargo commands on each crate without changing the working directory all the times via Subshells (A command list embedded between parentheses). For example, if you are in the greetings directory, even you run (cd examples/hello && cargo run) your working directory will be kept as same in greetings folder.
\ No newline at end of file
diff --git a/docs/index.xml b/docs/index.xml
new file mode 100644
index 0000000..ffaf921
--- /dev/null
+++ b/docs/index.xml
@@ -0,0 +1,503 @@
+Learning Rusthttps://learning-rust.github.io/Recent content on Learning RustHugoen-USBorrowinghttps://learning-rust.github.io/docs/borrowing/Mon, 01 Jan 0001 00:00:00 +0000https://learning-rust.github.io/docs/borrowing/<p>In real life applications, most of the times we have to pass variable bindings to other functions or assign them to other variable bindings. In this case, we are <strong>referencing</strong> the original binding; <strong>borrow</strong> the data of it.</p>
+<h2 id="what-is-borrowing">What is Borrowing?</h2>
+<blockquote>
+<p><a href="https://github.com/nikomatsakis/rust-tutorials-keynote/blob/master/Ownership%20and%20Borrowing.pdf" target="_blank" >Borrow (verb)</a><br>
+To receive something with the promise of returning it.</p></blockquote>
+<h2 id="shared--mutable-borrowings">Shared & Mutable borrowings</h2>
+<p>βοΈ There are two types of Borrowing,</p>
+<ol>
+<li>
+<p><strong>Shared Borrowing</strong> <code>(&T)</code></p>
+<ul>
+<li>A piece of data can be <strong>borrowed by a single or multiple users</strong>, but <strong>data should not be altered</strong>.</li>
+</ul>
+</li>
+<li>
+<p><strong>Mutable Borrowing</strong> <code>(&mut T)</code></p>Cargo, Crates and Basic Project Structurehttps://learning-rust.github.io/docs/cargo-crates-and-basic-project-structure/Mon, 01 Jan 0001 00:00:00 +0000https://learning-rust.github.io/docs/cargo-crates-and-basic-project-structure/<h2 id="cargo">Cargo</h2>
+<p>Cargo is Rustβs built-in package manager and build system. It also supports the following actions,</p>
+<table>
+ <thead>
+ <tr>
+ <th>Command</th>
+ <th>Action</th>
+ </tr>
+ </thead>
+ <tbody>
+ <tr>
+ <td><code>cargo new</code></td>
+ <td>Create a new project</td>
+ </tr>
+ <tr>
+ <td><code>cargo init</code></td>
+ <td>Create a new project in an existing directory</td>
+ </tr>
+ <tr>
+ <td><code>cargo check</code></td>
+ <td>Verify the project compiles without errors</td>
+ </tr>
+ <tr>
+ <td><code>cargo build</code></td>
+ <td>Build the executable</td>
+ </tr>
+ <tr>
+ <td><code>cargo run</code></td>
+ <td>Build the executable and run</td>
+ </tr>
+ </tbody>
+</table>
+<blockquote>
+<p>π‘ The <code>cargo check</code> command verifies that the project compiles without errors, without producing an executable.
+Thus, it is often faster than <code>cargo build</code>.</p>Code Organizationhttps://learning-rust.github.io/docs/code-organization/Mon, 01 Jan 0001 00:00:00 +0000https://learning-rust.github.io/docs/code-organization/<p>When a single code block is getting larger, it should be decomposed into smaller pieces and should be organized in a proper manner. Rust supports different levels of code organization.</p>
+<h2 id="1-functions">1. Functions</h2>
+<h2 id="2-modules">2. Modules</h2>
+<p>Can be mapped to a,</p>
+<ul>
+<li><strong>Inline module</strong></li>
+<li><strong>File</strong></li>
+<li><strong>Directory hierarchy</strong></li>
+</ul>
+<h2 id="3-crates">3. Crates</h2>
+<p>Can be mapped to a,</p>
+<ul>
+<li>
+<p><strong>lib.rs file on the same executable crate</strong></p>
+</li>
+<li>
+<p><strong>Dependency crate specified on Cargo.toml</strong></p>
+<p>Can be specified from,</p>
+<ul>
+<li><strong>Path</strong></li>
+<li><strong>Git repository</strong></li>
+<li><strong>crates.io</strong></li>
+</ul>
+</li>
+</ul>
+<h2 id="4-workspaces">4. Workspaces</h2>
+<p>Helps to manage multiple crates as a single project.</p>Combinatorshttps://learning-rust.github.io/docs/combinators/Mon, 01 Jan 0001 00:00:00 +0000https://learning-rust.github.io/docs/combinators/<h2 id="what-is-a-combinator">What is a combinator?</h2>
+<ul>
+<li>
+<p>One meaning of βcombinatorβ is a more informal sense referring to the <strong>combinator pattern</strong>, a style of organizing libraries centered around the idea of combining things. Usually there is <strong>some type T</strong>, some <strong>functions for constructing βprimitiveβ values of type T</strong>, and some β<strong>combinators</strong>β which can <strong>combine values of type T</strong> in various ways to <strong>build up more complex values of type T</strong>. The other definition is <strong>“function with no free variables”</strong>.
+__ <a href="https://wiki.haskell.org/Combinator" target="_blank" >wiki.haskell.org</a></p>Comments and Documenting the codehttps://learning-rust.github.io/docs/comments-and-documenting-the-code/Mon, 01 Jan 0001 00:00:00 +0000https://learning-rust.github.io/docs/comments-and-documenting-the-code/<h2 id="comments">Comments</h2>
+<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-rust" data-lang="rust"><span class="line"><span class="cl"><span class="c1">// Line comments
+</span></span></span><span class="line"><span class="cl"><span class="c1"></span><span class="cm">/* Block comments */</span><span class="w">
+</span></span></span></code></pre></div><p>Nested block comments are supported.</p>
+<p>π‘ <strong>By convention, try to avoid using block comments. Use line comments instead.</strong></p>
+<h2 id="doc-comments">Doc Comments</h2>
+<p><a href="https://learning-rust.github.io/docs/cargo-crates-and-basic-project-structure/#cargo" >As we discussed</a>, we can generate the project documentation via <a href="https://doc.rust-lang.org/stable/rustdoc/" target="_blank" >rustdoc</a> by running the <strong><code>cargo doc</code></strong> command. It uses the doc comments to generate the documentation.</p>
+<p>π‘ Usually we are adding doc comments on library crates. Also, we can use <a href="https://github.com/adam-p/markdown-here/wiki/Markdown-Cheatsheet" target="_blank" >Markdown notations</a> inside the doc comments.</p>Control Flowshttps://learning-rust.github.io/docs/control-flows/Mon, 01 Jan 0001 00:00:00 +0000https://learning-rust.github.io/docs/control-flows/<h2 id="if---else-if---else">if - else if - else</h2>
+<ul>
+<li>Using only <code>if</code> block.</li>
+</ul>
+<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-rust" data-lang="rust"><span class="line"><span class="cl"><span class="kd">let</span><span class="w"> </span><span class="n">age</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="mi">13</span><span class="p">;</span><span class="w">
+</span></span></span><span class="line"><span class="cl"><span class="w">
+</span></span></span><span class="line"><span class="cl"><span class="w"></span><span class="k">if</span><span class="w"> </span><span class="n">age</span><span class="w"> </span><span class="o"><</span><span class="w"> </span><span class="mi">18</span><span class="w"> </span><span class="p">{</span><span class="w">
+</span></span></span><span class="line"><span class="cl"><span class="w"> </span><span class="fm">println!</span><span class="p">(</span><span class="s">"Hello, child!"</span><span class="p">);</span><span class="w"> </span><span class="c1">// The code prints this
+</span></span></span><span class="line"><span class="cl"><span class="c1"></span><span class="p">}</span><span class="w">
+</span></span></span></code></pre></div><ul>
+<li>Using only <code>if</code> and <code>else</code> blocks.</li>
+</ul>
+<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-rust" data-lang="rust"><span class="line"><span class="cl"><span class="kd">let</span><span class="w"> </span><span class="n">i</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="mi">7</span><span class="p">;</span><span class="w">
+</span></span></span><span class="line"><span class="cl"><span class="w">
+</span></span></span><span class="line"><span class="cl"><span class="w"></span><span class="k">if</span><span class="w"> </span><span class="n">i</span><span class="w"> </span><span class="o">%</span><span class="w"> </span><span class="mi">2</span><span class="w"> </span><span class="o">==</span><span class="w"> </span><span class="mi">0</span><span class="w"> </span><span class="p">{</span><span class="w">
+</span></span></span><span class="line"><span class="cl"><span class="w"> </span><span class="fm">println!</span><span class="p">(</span><span class="s">"Even"</span><span class="p">);</span><span class="w">
+</span></span></span><span class="line"><span class="cl"><span class="w"></span><span class="p">}</span><span class="w"> </span><span class="k">else</span><span class="w"> </span><span class="p">{</span><span class="w">
+</span></span></span><span class="line"><span class="cl"><span class="w"> </span><span class="fm">println!</span><span class="p">(</span><span class="s">"Odd"</span><span class="p">);</span><span class="w"> </span><span class="c1">// The code prints this
+</span></span></span><span class="line"><span class="cl"><span class="c1"></span><span class="p">}</span><span class="w">
+</span></span></span></code></pre></div><ul>
+<li>Using with <code>let</code> statement.</li>
+</ul>
+<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-rust" data-lang="rust"><span class="line"><span class="cl"><span class="kd">let</span><span class="w"> </span><span class="n">age</span>: <span class="kt">u8</span> <span class="o">=</span><span class="w"> </span><span class="mi">13</span><span class="p">;</span><span class="w">
+</span></span></span><span class="line"><span class="cl"><span class="w"></span><span class="kd">let</span><span class="w"> </span><span class="n">is_below_eighteen</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="k">if</span><span class="w"> </span><span class="n">age</span><span class="w"> </span><span class="o"><</span><span class="w"> </span><span class="mi">18</span><span class="w"> </span><span class="p">{</span><span class="w"> </span><span class="kc">true</span><span class="w"> </span><span class="p">}</span><span class="w"> </span><span class="k">else</span><span class="w"> </span><span class="p">{</span><span class="w"> </span><span class="kc">false</span><span class="w"> </span><span class="p">};</span><span class="w"> </span><span class="c1">// true
+</span></span></span></code></pre></div><ul>
+<li>More examples,</li>
+</ul>
+<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-rust" data-lang="rust"><span class="line"><span class="cl"><span class="c1">// i. A simple example
+</span></span></span><span class="line"><span class="cl"><span class="c1"></span><span class="kd">let</span><span class="w"> </span><span class="n">team_size</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="mi">7</span><span class="p">;</span><span class="w">
+</span></span></span><span class="line"><span class="cl"><span class="w">
+</span></span></span><span class="line"><span class="cl"><span class="w"></span><span class="k">if</span><span class="w"> </span><span class="n">team_size</span><span class="w"> </span><span class="o"><</span><span class="w"> </span><span class="mi">5</span><span class="w"> </span><span class="p">{</span><span class="w">
+</span></span></span><span class="line"><span class="cl"><span class="w"> </span><span class="fm">println!</span><span class="p">(</span><span class="s">"Small"</span><span class="p">);</span><span class="w">
+</span></span></span><span class="line"><span class="cl"><span class="w"></span><span class="p">}</span><span class="w"> </span><span class="k">else</span><span class="w"> </span><span class="k">if</span><span class="w"> </span><span class="n">team_size</span><span class="w"> </span><span class="o"><</span><span class="w"> </span><span class="mi">10</span><span class="w"> </span><span class="p">{</span><span class="w">
+</span></span></span><span class="line"><span class="cl"><span class="w"> </span><span class="fm">println!</span><span class="p">(</span><span class="s">"Medium"</span><span class="p">);</span><span class="w"> </span><span class="c1">// The code prints this
+</span></span></span><span class="line"><span class="cl"><span class="c1"></span><span class="p">}</span><span class="w"> </span><span class="k">else</span><span class="w"> </span><span class="p">{</span><span class="w">
+</span></span></span><span class="line"><span class="cl"><span class="w"> </span><span class="fm">println!</span><span class="p">(</span><span class="s">"Large"</span><span class="p">);</span><span class="w">
+</span></span></span><span class="line"><span class="cl"><span class="w"></span><span class="p">}</span><span class="w">
+</span></span></span></code></pre></div><div class="highlight"><pre tabindex="0" class="chroma"><code class="language-rust" data-lang="rust"><span class="line"><span class="cl"><span class="c1">// ii. Let's refactor above code
+</span></span></span><span class="line"><span class="cl"><span class="c1"></span><span class="kd">let</span><span class="w"> </span><span class="n">team_size</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="mi">7</span><span class="p">;</span><span class="w">
+</span></span></span><span class="line"><span class="cl"><span class="w"></span><span class="kd">let</span><span class="w"> </span><span class="n">team_size_in_text</span><span class="p">;</span><span class="w">
+</span></span></span><span class="line"><span class="cl"><span class="w">
+</span></span></span><span class="line"><span class="cl"><span class="w"></span><span class="k">if</span><span class="w"> </span><span class="n">team_size</span><span class="w"> </span><span class="o"><</span><span class="w"> </span><span class="mi">5</span><span class="w"> </span><span class="p">{</span><span class="w">
+</span></span></span><span class="line"><span class="cl"><span class="w"> </span><span class="n">team_size_in_text</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="s">"Small"</span><span class="p">;</span><span class="w">
+</span></span></span><span class="line"><span class="cl"><span class="w"></span><span class="p">}</span><span class="w"> </span><span class="k">else</span><span class="w"> </span><span class="k">if</span><span class="w"> </span><span class="n">team_size</span><span class="w"> </span><span class="o"><</span><span class="w"> </span><span class="mi">10</span><span class="w"> </span><span class="p">{</span><span class="w">
+</span></span></span><span class="line"><span class="cl"><span class="w"> </span><span class="n">team_size_in_text</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="s">"Medium"</span><span class="p">;</span><span class="w">
+</span></span></span><span class="line"><span class="cl"><span class="w"></span><span class="p">}</span><span class="w"> </span><span class="k">else</span><span class="w"> </span><span class="p">{</span><span class="w">
+</span></span></span><span class="line"><span class="cl"><span class="w"> </span><span class="n">team_size_in_text</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="s">"Large"</span><span class="p">;</span><span class="w">
+</span></span></span><span class="line"><span class="cl"><span class="w"></span><span class="p">}</span><span class="w">
+</span></span></span><span class="line"><span class="cl"><span class="w">
+</span></span></span><span class="line"><span class="cl"><span class="w"></span><span class="fm">println!</span><span class="p">(</span><span class="s">"Current team size : </span><span class="si">{}</span><span class="s">"</span><span class="p">,</span><span class="w"> </span><span class="n">team_size_in_text</span><span class="p">);</span><span class="w"> </span><span class="c1">// Current team size : Medium
+</span></span></span></code></pre></div><div class="highlight"><pre tabindex="0" class="chroma"><code class="language-rust" data-lang="rust"><span class="line"><span class="cl"><span class="c1">// iii. Let's refactor further
+</span></span></span><span class="line"><span class="cl"><span class="c1"></span><span class="kd">let</span><span class="w"> </span><span class="n">team_size</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="mi">7</span><span class="p">;</span><span class="w">
+</span></span></span><span class="line"><span class="cl"><span class="w"></span><span class="kd">let</span><span class="w"> </span><span class="n">team_size</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="k">if</span><span class="w"> </span><span class="n">team_size</span><span class="w"> </span><span class="o"><</span><span class="w"> </span><span class="mi">5</span><span class="w"> </span><span class="p">{</span><span class="w">
+</span></span></span><span class="line"><span class="cl"><span class="w"> </span><span class="s">"Small"</span><span class="w"> </span><span class="c1">// βοΈ no ;
+</span></span></span><span class="line"><span class="cl"><span class="c1"></span><span class="p">}</span><span class="w"> </span><span class="k">else</span><span class="w"> </span><span class="k">if</span><span class="w"> </span><span class="n">team_size</span><span class="w"> </span><span class="o"><</span><span class="w"> </span><span class="mi">10</span><span class="w"> </span><span class="p">{</span><span class="w">
+</span></span></span><span class="line"><span class="cl"><span class="w"> </span><span class="s">"Medium"</span><span class="w">
+</span></span></span><span class="line"><span class="cl"><span class="w"></span><span class="p">}</span><span class="w"> </span><span class="k">else</span><span class="w"> </span><span class="p">{</span><span class="w">
+</span></span></span><span class="line"><span class="cl"><span class="w"> </span><span class="s">"Large"</span><span class="w">
+</span></span></span><span class="line"><span class="cl"><span class="w"></span><span class="p">};</span><span class="w">
+</span></span></span><span class="line"><span class="cl"><span class="w">
+</span></span></span><span class="line"><span class="cl"><span class="w"></span><span class="fm">println!</span><span class="p">(</span><span class="s">"Current team size : </span><span class="si">{}</span><span class="s">"</span><span class="p">,</span><span class="w"> </span><span class="n">team_size</span><span class="p">);</span><span class="w"> </span><span class="c1">// Current team size : Medium
+</span></span></span></code></pre></div><p>βοΈ <strong>Return data type should be the same on each block when using this as an expression.</strong></p>Crateshttps://learning-rust.github.io/docs/crates/Mon, 01 Jan 0001 00:00:00 +0000https://learning-rust.github.io/docs/crates/<p>π Crates are a bit similar to the packages in some other languages. Crates compile individually. If the crate has child file modules, those files will get merged with the crate file and compile as a single unit.</p>
+<p>π A crate can produce an executable/ a binary or a library. <code>src/main.rs</code> is the crate root/ entry point for a binary crate and <code>src/lib.rs</code> is the entry point for a library crate.</p>Custom Error Typeshttps://learning-rust.github.io/docs/custom-error-types/Mon, 01 Jan 0001 00:00:00 +0000https://learning-rust.github.io/docs/custom-error-types/<p>Rust allow us to create our own <code>Err</code> types. We call them β<em>Custom Error Types</em>β.</p>
+<h2 id="error-trait">Error trait</h2>
+<p>As you know <strong>traits define the functionality a type must provide</strong>. But we donβt always need to define new traits for common functionalities, because Rust <strong>standard library provides reusable traits</strong> which can be implemented on our own types. While creating custom error types the <a href="https://doc.rust-lang.org/std/error/trait.Error.html" target="_blank" ><code>std::error::Error</code> trait</a> helps us to convert any type to an <code>Err</code> type.</p>Enumshttps://learning-rust.github.io/docs/enums/Mon, 01 Jan 0001 00:00:00 +0000https://learning-rust.github.io/docs/enums/<p>βοΈ An <strong>enum</strong> is a single type. It contains <strong>variants</strong>, which are possible values of the enum at a given time. For example,</p>
+<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-rust" data-lang="rust"><span class="line"><span class="cl"><span class="k">enum</span> <span class="nc">Day</span><span class="w"> </span><span class="p">{</span><span class="w">
+</span></span></span><span class="line"><span class="cl"><span class="w"> </span><span class="n">Sunday</span><span class="p">,</span><span class="w">
+</span></span></span><span class="line"><span class="cl"><span class="w"> </span><span class="n">Monday</span><span class="p">,</span><span class="w">
+</span></span></span><span class="line"><span class="cl"><span class="w"> </span><span class="n">Tuesday</span><span class="p">,</span><span class="w">
+</span></span></span><span class="line"><span class="cl"><span class="w"> </span><span class="n">Wednesday</span><span class="p">,</span><span class="w">
+</span></span></span><span class="line"><span class="cl"><span class="w"> </span><span class="n">Thursday</span><span class="p">,</span><span class="w">
+</span></span></span><span class="line"><span class="cl"><span class="w"> </span><span class="n">Friday</span><span class="p">,</span><span class="w">
+</span></span></span><span class="line"><span class="cl"><span class="w"> </span><span class="n">Saturday</span><span class="w">
+</span></span></span><span class="line"><span class="cl"><span class="w"></span><span class="p">}</span><span class="w">
+</span></span></span><span class="line"><span class="cl"><span class="w">
+</span></span></span><span class="line"><span class="cl"><span class="w"></span><span class="c1">// The `Day` is the enum
+</span></span></span><span class="line"><span class="cl"><span class="c1">// Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday are the variants
+</span></span></span></code></pre></div><p>βοΈ Variants can be accessed throughΒ :: notation, ex. Day::Sunday</p>
+<p>βοΈ Each enum <strong>variant</strong> can have,</p>Error and None Propagationhttps://learning-rust.github.io/docs/error-and-none-propagation/Mon, 01 Jan 0001 00:00:00 +0000https://learning-rust.github.io/docs/error-and-none-propagation/<p>We should use panics like <code>panic!()</code>, <code>unwrap()</code>, <code>expect()</code> only if we can not handle the situation in a better way. Also if a function contains expressions which can produce either <code>None</code> or <code>Err</code>,</p>
+<ul>
+<li>we can handle them inside the same function. Or,</li>
+<li>we can return <code>None</code> and <code>Err</code> types immediately to the caller. So the caller can decide how to handle them.</li>
+</ul>
+<p>π‘ <code>None</code> types no need to handle by the caller of the function always. But Rustsβ convention to handle <strong><code>Err</code></strong> types is, <strong>return them immediately to the caller to give more control to the caller to decide how to handle them.</strong></p>Functionshttps://learning-rust.github.io/docs/functions/Mon, 01 Jan 0001 00:00:00 +0000https://learning-rust.github.io/docs/functions/<h2 id="named-functions">Named functions</h2>
+<ul>
+<li>Named functions are declared with the keyword <strong><code>fn</code></strong></li>
+<li>When using <strong>arguments</strong>, you <strong>must declare the data types</strong>.</li>
+<li>By default, functions <strong>return an empty <a href="https://learning-rust.github.io/docs/primitive-data-types/#tuple" >tuple</a>/ <code>()</code></strong>. If you want to return a value, the <strong>return type must be specified</strong> after <strong><code>-></code></strong></li>
+</ul>
+<h3 id="i-hello-world">i. Hello world</h3>
+<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-rust" data-lang="rust"><span class="line"><span class="cl"><span class="k">fn</span> <span class="nf">main</span><span class="p">()</span><span class="w"> </span><span class="p">{</span><span class="w">
+</span></span></span><span class="line"><span class="cl"><span class="w"> </span><span class="fm">println!</span><span class="p">(</span><span class="s">"Hello, world!"</span><span class="p">);</span><span class="w">
+</span></span></span><span class="line"><span class="cl"><span class="w"></span><span class="p">}</span><span class="w">
+</span></span></span></code></pre></div><h3 id="ii-passing-arguments">ii. Passing arguments</h3>
+<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-rust" data-lang="rust"><span class="line"><span class="cl"><span class="k">fn</span> <span class="nf">print_sum</span><span class="p">(</span><span class="n">a</span>: <span class="kt">i8</span><span class="p">,</span><span class="w"> </span><span class="n">b</span>: <span class="kt">i8</span><span class="p">)</span><span class="w"> </span><span class="p">{</span><span class="w">
+</span></span></span><span class="line"><span class="cl"><span class="w"> </span><span class="fm">println!</span><span class="p">(</span><span class="s">"sum is: </span><span class="si">{}</span><span class="s">"</span><span class="p">,</span><span class="w"> </span><span class="n">a</span><span class="w"> </span><span class="o">+</span><span class="w"> </span><span class="n">b</span><span class="p">);</span><span class="w">
+</span></span></span><span class="line"><span class="cl"><span class="w"></span><span class="p">}</span><span class="w">
+</span></span></span></code></pre></div><h3 id="iii-returning-values">iii. Returning values</h3>
+<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-rust" data-lang="rust"><span class="line"><span class="cl"><span class="c1">// 01. Without the return keyword. Only the last expression returns.
+</span></span></span><span class="line"><span class="cl"><span class="c1"></span><span class="k">fn</span> <span class="nf">plus_one</span><span class="p">(</span><span class="n">a</span>: <span class="kt">i32</span><span class="p">)</span><span class="w"> </span>-> <span class="kt">i32</span> <span class="p">{</span><span class="w">
+</span></span></span><span class="line"><span class="cl"><span class="w"> </span><span class="n">a</span><span class="w"> </span><span class="o">+</span><span class="w"> </span><span class="mi">1</span><span class="w">
+</span></span></span><span class="line"><span class="cl"><span class="w"> </span><span class="c1">// There is no ending ; in the above line.
+</span></span></span><span class="line"><span class="cl"><span class="c1"></span><span class="w"> </span><span class="c1">// It means this is an expression which equals to `return a + 1;`.
+</span></span></span><span class="line"><span class="cl"><span class="c1"></span><span class="p">}</span><span class="w">
+</span></span></span></code></pre></div><div class="highlight"><pre tabindex="0" class="chroma"><code class="language-rust" data-lang="rust"><span class="line"><span class="cl"><span class="c1">// 02. With the return keyword.
+</span></span></span><span class="line"><span class="cl"><span class="c1"></span><span class="k">fn</span> <span class="nf">plus_two</span><span class="p">(</span><span class="n">a</span>: <span class="kt">i32</span><span class="p">)</span><span class="w"> </span>-> <span class="kt">i32</span> <span class="p">{</span><span class="w">
+</span></span></span><span class="line"><span class="cl"><span class="w"> </span><span class="k">return</span><span class="w"> </span><span class="n">a</span><span class="w"> </span><span class="o">+</span><span class="w"> </span><span class="mi">2</span><span class="p">;</span><span class="w">
+</span></span></span><span class="line"><span class="cl"><span class="w"> </span><span class="c1">// Should use return keyword only on conditional/ early returns.
+</span></span></span><span class="line"><span class="cl"><span class="c1"></span><span class="w"> </span><span class="c1">// Using return keyword in the last expression is a bad practice.
+</span></span></span><span class="line"><span class="cl"><span class="c1"></span><span class="p">}</span><span class="w">
+</span></span></span></code></pre></div><h3 id="iv-function-pointers-usage-as-a-data-type">iv. Function pointers, Usage as a Data Type</h3>
+<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-rust" data-lang="rust"><span class="line"><span class="cl"><span class="k">fn</span> <span class="nf">main</span><span class="p">()</span><span class="w"> </span><span class="p">{</span><span class="w">
+</span></span></span><span class="line"><span class="cl"><span class="w"> </span><span class="c1">// 01. Without type declarations.
+</span></span></span><span class="line"><span class="cl"><span class="c1"></span><span class="w"> </span><span class="kd">let</span><span class="w"> </span><span class="n">p1</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="n">plus_one</span><span class="p">;</span><span class="w">
+</span></span></span><span class="line"><span class="cl"><span class="w"> </span><span class="kd">let</span><span class="w"> </span><span class="n">x</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="n">p1</span><span class="p">(</span><span class="mi">5</span><span class="p">);</span><span class="w"> </span><span class="c1">// 6
+</span></span></span><span class="line"><span class="cl"><span class="c1"></span><span class="w">
+</span></span></span><span class="line"><span class="cl"><span class="w"> </span><span class="c1">// 02. With type declarations.
+</span></span></span><span class="line"><span class="cl"><span class="c1"></span><span class="w"> </span><span class="kd">let</span><span class="w"> </span><span class="n">p1</span>: <span class="nc">fn</span><span class="p">(</span><span class="kt">i32</span><span class="p">)</span><span class="w"> </span>-> <span class="kt">i32</span> <span class="o">=</span><span class="w"> </span><span class="n">plus_one</span><span class="p">;</span><span class="w">
+</span></span></span><span class="line"><span class="cl"><span class="w"> </span><span class="kd">let</span><span class="w"> </span><span class="n">x</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="n">p1</span><span class="p">(</span><span class="mi">5</span><span class="p">);</span><span class="w"> </span><span class="c1">// 6
+</span></span></span><span class="line"><span class="cl"><span class="c1"></span><span class="p">}</span><span class="w">
+</span></span></span><span class="line"><span class="cl"><span class="w">
+</span></span></span><span class="line"><span class="cl"><span class="w"></span><span class="k">fn</span> <span class="nf">plus_one</span><span class="p">(</span><span class="n">a</span>: <span class="kt">i32</span><span class="p">)</span><span class="w"> </span>-> <span class="kt">i32</span> <span class="p">{</span><span class="w">
+</span></span></span><span class="line"><span class="cl"><span class="w"> </span><span class="n">a</span><span class="w"> </span><span class="o">+</span><span class="w"> </span><span class="mi">1</span><span class="w">
+</span></span></span><span class="line"><span class="cl"><span class="w"></span><span class="p">}</span><span class="w">
+</span></span></span></code></pre></div><h2 id="closures">Closures</h2>
+<ul>
+<li>Also known as <strong>anonymous functions</strong> or <strong>lambda functions</strong>.</li>
+<li>The <strong>data types of arguments and returns are optional <a href="#iv-without-optional-type-declarations-creating-and-calling-together" > β°β±α΅</a></strong>.</li>
+</ul>
+<p>Example with a named function, before using closures.</p>Functions (02)https://learning-rust.github.io/docs/functions-02/Mon, 01 Jan 0001 00:00:00 +0000https://learning-rust.github.io/docs/functions-02/<p>Functions are the first line of organization in any program.</p>
+<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-rust" data-lang="rust"><span class="line"><span class="cl"><span class="k">fn</span> <span class="nf">main</span><span class="p">()</span><span class="w"> </span><span class="p">{</span><span class="w">
+</span></span></span><span class="line"><span class="cl"><span class="w"> </span><span class="n">greet</span><span class="p">();</span><span class="w"> </span><span class="c1">// Do one thing
+</span></span></span><span class="line"><span class="cl"><span class="c1"></span><span class="w"> </span><span class="n">ask_location</span><span class="p">();</span><span class="w"> </span><span class="c1">// Do another thing
+</span></span></span><span class="line"><span class="cl"><span class="c1"></span><span class="p">}</span><span class="w">
+</span></span></span><span class="line"><span class="cl"><span class="w">
+</span></span></span><span class="line"><span class="cl"><span class="w"></span><span class="k">fn</span> <span class="nf">greet</span><span class="p">()</span><span class="w"> </span><span class="p">{</span><span class="w">
+</span></span></span><span class="line"><span class="cl"><span class="w"> </span><span class="fm">println!</span><span class="p">(</span><span class="s">"Hello!"</span><span class="p">);</span><span class="w">
+</span></span></span><span class="line"><span class="cl"><span class="w"></span><span class="p">}</span><span class="w">
+</span></span></span><span class="line"><span class="cl"><span class="w">
+</span></span></span><span class="line"><span class="cl"><span class="w"></span><span class="k">fn</span> <span class="nf">ask_location</span><span class="p">()</span><span class="w"> </span><span class="p">{</span><span class="w">
+</span></span></span><span class="line"><span class="cl"><span class="w"> </span><span class="fm">println!</span><span class="p">(</span><span class="s">"Where are you from?"</span><span class="p">);</span><span class="w">
+</span></span></span><span class="line"><span class="cl"><span class="w"></span><span class="p">}</span><span class="w">
+</span></span></span></code></pre></div><p>We can add unit tests in the same file.</p>
+<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-rust" data-lang="rust"><span class="line"><span class="cl"><span class="k">fn</span> <span class="nf">main</span><span class="p">()</span><span class="w"> </span><span class="p">{</span><span class="w">
+</span></span></span><span class="line"><span class="cl"><span class="w"> </span><span class="n">greet</span><span class="p">();</span><span class="w">
+</span></span></span><span class="line"><span class="cl"><span class="w"></span><span class="p">}</span><span class="w">
+</span></span></span><span class="line"><span class="cl"><span class="w">
+</span></span></span><span class="line"><span class="cl"><span class="w"></span><span class="k">fn</span> <span class="nf">greet</span><span class="p">()</span><span class="w"> </span>-> <span class="nb">String</span> <span class="p">{</span><span class="w">
+</span></span></span><span class="line"><span class="cl"><span class="w"> </span><span class="s">"Hello, world!"</span><span class="p">.</span><span class="n">to_string</span><span class="p">()</span><span class="w">
+</span></span></span><span class="line"><span class="cl"><span class="w"></span><span class="p">}</span><span class="w">
+</span></span></span><span class="line"><span class="cl"><span class="w">
+</span></span></span><span class="line"><span class="cl"><span class="w"></span><span class="cp">#[test]</span><span class="w"> </span><span class="c1">// Test attribute indicates this is a test function
+</span></span></span><span class="line"><span class="cl"><span class="c1"></span><span class="k">fn</span> <span class="nf">test_greet</span><span class="p">()</span><span class="w"> </span><span class="p">{</span><span class="w">
+</span></span></span><span class="line"><span class="cl"><span class="w"> </span><span class="fm">assert_eq!</span><span class="p">(</span><span class="s">"Hello, world!"</span><span class="p">,</span><span class="w"> </span><span class="n">greet</span><span class="p">())</span><span class="w">
+</span></span></span><span class="line"><span class="cl"><span class="w"></span><span class="p">}</span><span class="w">
+</span></span></span><span class="line"><span class="cl"><span class="w">
+</span></span></span><span class="line"><span class="cl"><span class="w"></span><span class="c1">// π‘ Always put test functions inside a tests module with #[cfg(test)] attribute.
+</span></span></span><span class="line"><span class="cl"><span class="c1">// cfg(test) module compiles only when running tests. We discuss more about this in the next section.
+</span></span></span></code></pre></div><blockquote>
+<p>π An <a href="https://doc.rust-lang.org/reference/attributes.html" target="_blank" >attribute</a> is a general, free-form <strong>metadatum</strong> that is interpreted according to name, convention, and language and compiler version.</p>Genericshttps://learning-rust.github.io/docs/generics/Mon, 01 Jan 0001 00:00:00 +0000https://learning-rust.github.io/docs/generics/<blockquote>
+<p><a href="https://doc.rust-lang.org/beta/book/first-edition/generics.html" target="_blank" >π</a> Sometimes, when writing a function or data type, we may want it to work for multiple types of arguments. In Rust, we can do this with generics.</p></blockquote>
+<p>π The concept is, instead of declaring a specific data type we use an uppercase letter(or <a href="https://en.wikipedia.org/wiki/Camel_case" target="_blank" >PascalCase</a> identifier). ex, <strong>instead of xΒ : u8</strong> we use <strong>xΒ : T</strong>Β . but we have to inform to the compiler that T is a generic type(can be any type) by adding <code><T></code> at first.</p>Hello Worldhttps://learning-rust.github.io/docs/hello-world/Mon, 01 Jan 0001 00:00:00 +0000https://learning-rust.github.io/docs/hello-world/<h2 id="hello-world">Hello, World!</h2>
+<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-rust" data-lang="rust"><span class="line"><span class="cl"><span class="k">fn</span> <span class="nf">main</span><span class="p">()</span><span class="w"> </span><span class="p">{</span><span class="w">
+</span></span></span><span class="line"><span class="cl"><span class="w"> </span><span class="fm">println!</span><span class="p">(</span><span class="s">"Hello, world!"</span><span class="p">);</span><span class="w">
+</span></span></span><span class="line"><span class="cl"><span class="w"></span><span class="p">}</span><span class="w">
+</span></span></span></code></pre></div><p><code>fn</code> means function. The <code>main</code> function is the beginning of every Rust program.<br>
+<code>println!()</code> prints text to the console and its <code>!</code> indicates that itβs a <a href="https://doc.rust-lang.org/book/ch19-06-macros.html" target="_blank" >macro</a> rather than a function.</p>
+<blockquote>
+<p>π‘ Rust files should have <code>.rs</code> file extension and if youβre using more than one word for the file name, follow the <a href="https://en.wikipedia.org/wiki/Snake_case" target="_blank" >snake_case</a> convention.</p></blockquote>
+<ul>
+<li>Save the above code in <code>file.rs</code> , but it can be any name with <code>.rs</code> extension.</li>
+<li>Compile it with <code>rustc file.rs</code></li>
+<li>Execute it with <code>./file</code> on Linux and Mac or <code>file.exe</code> on Windows</li>
+</ul>
+<h2 id="rust-playground">Rust Playground</h2>
+<p><a href="https://play.rust-lang.org/" target="_blank" >Rust Playground</a> is a web interface for running Rust code.</p>Impls & Traitshttps://learning-rust.github.io/docs/impls-and-traits/Mon, 01 Jan 0001 00:00:00 +0000https://learning-rust.github.io/docs/impls-and-traits/<p>π‘ When we discussed about <strong>C-like structs</strong>, I mentioned that those are <strong>similar to classes</strong> in OOP languages <strong>but without their methods</strong>. <strong>impls</strong> are <strong>used to define methods</strong> for Rust structs and enums.</p>
+<p>π‘ <strong>Traits</strong> are kind of <strong>similar to interfaces</strong> in OOP languages. They are used to define the functionality a type must provide. Multiple traits can be implemented for a single type.</p>
+<p>βοΈοΈ But traits <strong>can also include default implementations of methods</strong>. Default methods can be overridden when implementing types.</p>Installationhttps://learning-rust.github.io/docs/installation/Mon, 01 Jan 0001 00:00:00 +0000https://learning-rust.github.io/docs/installation/<h2 id="rustup">Rustup</h2>
+<p>There are many ways to install Rust on your system. For the moment the official way to install Rust is using <a href="https://rustup.rs/" target="_blank" >Rustup</a>.</p>
+<p><a href="https://rust-lang.github.io/rustup/index.html" target="_blank" >π</a> Rustup installs The Rust Programming Language from the official release channels, enabling you to easily switch between <strong>stable, beta, and nightly</strong> compilers and keep them updated. It also makes cross-compiling simpler with binary builds of the standard library for common platforms.</p>
+<p><a href="https://rust-lang.github.io/rustup/installation/index.html" target="_blank" >π</a> Rustup installs <strong><code>rustc</code>, <code>cargo</code>, <code>rustup</code></strong> and other standard tools to Cargo’s <code>bin</code> directory. On Unix it is located at <code>$HOME/.cargo/bin</code> and on Windows at <code>%USERPROFILE%\.cargo\bin</code>. This is the same directory that <code>cargo install</code> will install Rust programs and Cargo plugins.</p>Lifetimeshttps://learning-rust.github.io/docs/lifetimes/Mon, 01 Jan 0001 00:00:00 +0000https://learning-rust.github.io/docs/lifetimes/<p>When we are dealing with references, we have to make sure that the referencing data stay alive until we stop using the references.</p>
+<p>Think,</p>
+<ul>
+<li>We have a <strong>variable binding</strong>, <code>a</code>.</li>
+<li>We are <strong>referencing</strong> the value of <code>a</code>, <strong>from another variable binding</strong> <code>x</code>.
+We have to make sure that <strong><code>a</code> lives until we stop using <code>x</code></strong>.</li>
+</ul>
+<blockquote>
+<p>π <strong>Memory management</strong> is a form of resource management applied to computer memory. Up until the mid-1990s, the majority of programming languages used <strong>Manual Memory Management</strong> which <strong>requires the programmer to give manual instructions</strong> to identify and deallocate unused objects/ garbage. Around 1959 John McCarthy invented <strong>Garbage collection</strong>(GC), a form of <strong>Automatic Memory Management</strong>(AMM). It determines what memory is no longer used and frees it automatically instead of relying on the programmer. However <strong>Objective-C and Swift</strong> provide similar functionality through <strong>Automatic Reference Counting</strong>(ARC).</p>Moduleshttps://learning-rust.github.io/docs/modules/Mon, 01 Jan 0001 00:00:00 +0000https://learning-rust.github.io/docs/modules/<h2 id="01-in-the-same-file">01. In the same file</h2>
+<p>Related code and data are grouped into a module and stored in the same file.</p>
+<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-rust" data-lang="rust"><span class="line"><span class="cl"><span class="k">fn</span> <span class="nf">main</span><span class="p">()</span><span class="w"> </span><span class="p">{</span><span class="w">
+</span></span></span><span class="line"><span class="cl"><span class="w"> </span><span class="n">greetings</span>::<span class="n">hello</span><span class="p">();</span><span class="w">
+</span></span></span><span class="line"><span class="cl"><span class="w"></span><span class="p">}</span><span class="w">
+</span></span></span><span class="line"><span class="cl"><span class="w">
+</span></span></span><span class="line"><span class="cl"><span class="w"></span><span class="k">mod</span> <span class="nn">greetings</span><span class="w"> </span><span class="p">{</span><span class="w">
+</span></span></span><span class="line"><span class="cl"><span class="w"> </span><span class="c1">// βοΈ By default, everything inside a module is private
+</span></span></span><span class="line"><span class="cl"><span class="c1"></span><span class="w"> </span><span class="k">pub</span><span class="w"> </span><span class="k">fn</span> <span class="nf">hello</span><span class="p">()</span><span class="w"> </span><span class="p">{</span><span class="w"> </span><span class="c1">// βοΈ So function has to be public to access from outside
+</span></span></span><span class="line"><span class="cl"><span class="c1"></span><span class="w"> </span><span class="fm">println!</span><span class="p">(</span><span class="s">"Hello, world!"</span><span class="p">);</span><span class="w">
+</span></span></span><span class="line"><span class="cl"><span class="w"> </span><span class="p">}</span><span class="w">
+</span></span></span><span class="line"><span class="cl"><span class="w"></span><span class="p">}</span><span class="w">
+</span></span></span></code></pre></div><p>Modules can also be nested.</p>
+<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-rust" data-lang="rust"><span class="line"><span class="cl"><span class="k">fn</span> <span class="nf">main</span><span class="p">()</span><span class="w"> </span><span class="p">{</span><span class="w">
+</span></span></span><span class="line"><span class="cl"><span class="w"> </span><span class="n">phrases</span>::<span class="n">greetings</span>::<span class="n">hello</span><span class="p">();</span><span class="w">
+</span></span></span><span class="line"><span class="cl"><span class="w"></span><span class="p">}</span><span class="w">
+</span></span></span><span class="line"><span class="cl"><span class="w">
+</span></span></span><span class="line"><span class="cl"><span class="w"></span><span class="k">mod</span> <span class="nn">phrases</span><span class="w"> </span><span class="p">{</span><span class="w">
+</span></span></span><span class="line"><span class="cl"><span class="w"> </span><span class="k">pub</span><span class="w"> </span><span class="k">mod</span> <span class="nn">greetings</span><span class="w"> </span><span class="p">{</span><span class="w">
+</span></span></span><span class="line"><span class="cl"><span class="w"> </span><span class="k">pub</span><span class="w"> </span><span class="k">fn</span> <span class="nf">hello</span><span class="p">()</span><span class="w"> </span><span class="p">{</span><span class="w">
+</span></span></span><span class="line"><span class="cl"><span class="w"> </span><span class="fm">println!</span><span class="p">(</span><span class="s">"Hello, world!"</span><span class="p">);</span><span class="w">
+</span></span></span><span class="line"><span class="cl"><span class="w"> </span><span class="p">}</span><span class="w">
+</span></span></span><span class="line"><span class="cl"><span class="w"> </span><span class="p">}</span><span class="w">
+</span></span></span><span class="line"><span class="cl"><span class="w"></span><span class="p">}</span><span class="w">
+</span></span></span></code></pre></div><p>Private functions can be called from the same module or from a child module.</p>Operatorshttps://learning-rust.github.io/docs/operators/Mon, 01 Jan 0001 00:00:00 +0000https://learning-rust.github.io/docs/operators/<ul>
+<li>
+<h2 id="arithmetic-operators">Arithmetic Operators</h2>
+</li>
+</ul>
+<p><code>+ - * / %</code></p>
+<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-rust" data-lang="rust"><span class="line"><span class="cl"><span class="kd">let</span><span class="w"> </span><span class="n">a</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="mi">5</span><span class="p">;</span><span class="w">
+</span></span></span><span class="line"><span class="cl"><span class="w"></span><span class="kd">let</span><span class="w"> </span><span class="n">b</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="n">a</span><span class="w"> </span><span class="o">+</span><span class="w"> </span><span class="mi">1</span><span class="p">;</span><span class="w"> </span><span class="c1">//6
+</span></span></span><span class="line"><span class="cl"><span class="c1"></span><span class="kd">let</span><span class="w"> </span><span class="n">c</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="n">a</span><span class="w"> </span><span class="o">-</span><span class="w"> </span><span class="mi">1</span><span class="p">;</span><span class="w"> </span><span class="c1">//4
+</span></span></span><span class="line"><span class="cl"><span class="c1"></span><span class="kd">let</span><span class="w"> </span><span class="n">d</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="n">a</span><span class="w"> </span><span class="o">*</span><span class="w"> </span><span class="mi">2</span><span class="p">;</span><span class="w"> </span><span class="c1">//10
+</span></span></span><span class="line"><span class="cl"><span class="c1"></span><span class="kd">let</span><span class="w"> </span><span class="n">e</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="n">a</span><span class="w"> </span><span class="o">/</span><span class="w"> </span><span class="mi">2</span><span class="p">;</span><span class="w"> </span><span class="c1">// βοΈ 2 not 2.5
+</span></span></span><span class="line"><span class="cl"><span class="c1"></span><span class="kd">let</span><span class="w"> </span><span class="n">f</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="n">a</span><span class="w"> </span><span class="o">%</span><span class="w"> </span><span class="mi">2</span><span class="p">;</span><span class="w"> </span><span class="c1">//1
+</span></span></span><span class="line"><span class="cl"><span class="c1"></span><span class="w">
+</span></span></span><span class="line"><span class="cl"><span class="w"></span><span class="kd">let</span><span class="w"> </span><span class="n">g</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="mf">5.0</span><span class="w"> </span><span class="o">/</span><span class="w"> </span><span class="mf">2.0</span><span class="p">;</span><span class="w"> </span><span class="c1">//2.5
+</span></span></span></code></pre></div><ul>
+<li>
+<h2 id="comparison-operators">Comparison Operators</h2>
+</li>
+</ul>
+<p><code>== != < > <= >=</code></p>
+<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-rust" data-lang="rust"><span class="line"><span class="cl"><span class="kd">let</span><span class="w"> </span><span class="n">a</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="mi">1</span><span class="p">;</span><span class="w">
+</span></span></span><span class="line"><span class="cl"><span class="w"></span><span class="kd">let</span><span class="w"> </span><span class="n">b</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="mi">2</span><span class="p">;</span><span class="w">
+</span></span></span><span class="line"><span class="cl"><span class="w">
+</span></span></span><span class="line"><span class="cl"><span class="w"></span><span class="kd">let</span><span class="w"> </span><span class="n">c</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="n">a</span><span class="w"> </span><span class="o">==</span><span class="w"> </span><span class="n">b</span><span class="p">;</span><span class="w"> </span><span class="c1">//false
+</span></span></span><span class="line"><span class="cl"><span class="c1"></span><span class="kd">let</span><span class="w"> </span><span class="n">d</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="n">a</span><span class="w"> </span><span class="o">!=</span><span class="w"> </span><span class="n">b</span><span class="p">;</span><span class="w"> </span><span class="c1">//true
+</span></span></span><span class="line"><span class="cl"><span class="c1"></span><span class="kd">let</span><span class="w"> </span><span class="n">e</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="n">a</span><span class="w"> </span><span class="o"><</span><span class="w"> </span><span class="n">b</span><span class="p">;</span><span class="w"> </span><span class="c1">//true
+</span></span></span><span class="line"><span class="cl"><span class="c1"></span><span class="kd">let</span><span class="w"> </span><span class="n">f</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="n">a</span><span class="w"> </span><span class="o">></span><span class="w"> </span><span class="n">b</span><span class="p">;</span><span class="w"> </span><span class="c1">//false
+</span></span></span><span class="line"><span class="cl"><span class="c1"></span><span class="kd">let</span><span class="w"> </span><span class="n">g</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="n">a</span><span class="w"> </span><span class="o"><=</span><span class="w"> </span><span class="n">a</span><span class="p">;</span><span class="w"> </span><span class="c1">//true
+</span></span></span><span class="line"><span class="cl"><span class="c1"></span><span class="kd">let</span><span class="w"> </span><span class="n">h</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="n">a</span><span class="w"> </span><span class="o">>=</span><span class="w"> </span><span class="n">a</span><span class="p">;</span><span class="w"> </span><span class="c1">//true
+</span></span></span><span class="line"><span class="cl"><span class="c1"></span><span class="w">
+</span></span></span><span class="line"><span class="cl"><span class="w"></span><span class="c1">// π
+</span></span></span><span class="line"><span class="cl"><span class="c1"></span><span class="kd">let</span><span class="w"> </span><span class="n">i</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="kc">true</span><span class="w"> </span><span class="o">></span><span class="w"> </span><span class="kc">false</span><span class="p">;</span><span class="w"> </span><span class="c1">//true
+</span></span></span><span class="line"><span class="cl"><span class="c1"></span><span class="kd">let</span><span class="w"> </span><span class="n">j</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="sc">'a'</span><span class="w"> </span><span class="o">></span><span class="w"> </span><span class="sc">'A'</span><span class="p">;</span><span class="w"> </span><span class="c1">//true
+</span></span></span></code></pre></div><ul>
+<li>
+<h2 id="logical-operators">Logical Operators</h2>
+</li>
+</ul>
+<p><code>! && ||</code></p>Option and Resulthttps://learning-rust.github.io/docs/option-and-result/Mon, 01 Jan 0001 00:00:00 +0000https://learning-rust.github.io/docs/option-and-result/<h2 id="why-option-and-result">Why Option and Result?</h2>
+<p>Many languages use <strong><code>null</code>\ <code>nil</code>\ <code>undefined</code> types</strong> to represent empty outputs, and <strong><code>Exceptions</code></strong> to handle errors. Rust skips using both, especially to prevent issues like <strong>null pointer exceptions, sensitive data leakages through exceptions</strong>, etc. Instead, Rust provides two special <strong>generic enums</strong>;<code>Option</code> and <code>Result</code> to deal with above cases.</p>
+<blockquote>
+<p>π In the previous sections, we have discussed about the basics of <a href="https://learning-rust.github.io/docs/enums" >enums</a>, <a href="https://learning-rust.github.io/docs/generics" >generics</a> and <a href="https://learning-rust.github.io/docs/generics/#generalizing-enums" ><code>Result</code> & <code>Option</code> types</a>.</p>Overviewhttps://learning-rust.github.io/docs/overview/Mon, 01 Jan 0001 00:00:00 +0000https://learning-rust.github.io/docs/overview/<h2 id="about-me">About me</h2>
+<blockquote>
+<p>π§βπ» I am an expat working in Singapore as a Go Backend and DevOps Engineer. Feel free to reach out if you find any mistakes or anything that needs to be changed, including spelling or grammar errors. Alternatively, you can create a pull request, open an issue, or <a href="https://gist.github.com/dumindu/00a0be2d175ed5ff3bc3c17bbf1ca5b6" target="_blank" >share your awesome ideas in this gist</a>. Good luck with learning Rust!</p></blockquote>
+<p><a href="https://github.com/learning-rust/learning-rust.github.io" target="_blank" ><img src="https://img.shields.io/github/stars/learning-rust/learning-rust.github.io?style=for-the-badge&logo=rust&label=learning-rust.github.io&logoColor=333333&labelColor=f9f9f9&color=F46623" alt="learning-rust.github.io"></a>
+<a href="https://learning-cloud-native-go.github.io" target="_blank" ><img src="https://img.shields.io/github/stars/learning-cloud-native-go/learning-cloud-native-go.github.io?style=for-the-badge&logo=go&logoColor=333333&label=learning-cloud-native-go.github.io&labelColor=f9f9f9&color=00ADD8" alt="learning-cloud-native-go.github.io"></a></p>
+<p><a href="https://github.com/dumindu" target="_blank" ><img src="https://img.shields.io/badge/dumindu-866ee7?style=for-the-badge&logo=GitHub&logoColor=333333&labelColor=f9f9f9" alt="github.com"></a>
+<a href="https://www.buymeacoffee.com/dumindu" target="_blank" ><img src="https://img.shields.io/badge/Buy%20me%20a%20coffee-dumindu-FFDD00?style=for-the-badge&logo=buymeacoffee&logoColor=333333&labelColor=f9f9f9" alt="buymeacoffee"></a></p>
+<h2 id="overview">Overview</h2>
+<p>This publication has its origins in the posts I authored on Medium at <a href="https://medium.com/learning-rust" target="_blank" >https://medium.com/learning-rust</a>. However, please note that I have ceased updating the Medium posts. All current and future updates, new content, code, and grammar fixes will be exclusively maintained and released here, <a href="https://learning-rust.github.io" target="_blank" >https://learning-rust.github.io</a>.</p>Ownershiphttps://learning-rust.github.io/docs/ownership/Mon, 01 Jan 0001 00:00:00 +0000https://learning-rust.github.io/docs/ownership/<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-rust" data-lang="rust"><span class="line"><span class="cl"><span class="k">fn</span> <span class="nf">main</span><span class="p">()</span><span class="w"> </span><span class="p">{</span><span class="w">
+</span></span></span><span class="line"><span class="cl"><span class="w"> </span><span class="kd">let</span><span class="w"> </span><span class="n">a</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="p">[</span><span class="mi">1</span><span class="p">,</span><span class="w"> </span><span class="mi">2</span><span class="p">,</span><span class="w"> </span><span class="mi">3</span><span class="p">];</span><span class="w">
+</span></span></span><span class="line"><span class="cl"><span class="w"> </span><span class="kd">let</span><span class="w"> </span><span class="n">b</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="n">a</span><span class="p">;</span><span class="w">
+</span></span></span><span class="line"><span class="cl"><span class="w"> </span><span class="fm">println!</span><span class="p">(</span><span class="s">"</span><span class="si">{:?}</span><span class="s"> </span><span class="si">{:?}</span><span class="s">"</span><span class="p">,</span><span class="w"> </span><span class="n">a</span><span class="p">,</span><span class="w"> </span><span class="n">b</span><span class="p">);</span><span class="w"> </span><span class="c1">// [1, 2, 3] [1, 2, 3]
+</span></span></span><span class="line"><span class="cl"><span class="c1"></span><span class="p">}</span><span class="w">
+</span></span></span><span class="line"><span class="cl"><span class="w">
+</span></span></span><span class="line"><span class="cl"><span class="w"></span><span class="k">fn</span> <span class="nf">main</span><span class="p">()</span><span class="w"> </span><span class="p">{</span><span class="w">
+</span></span></span><span class="line"><span class="cl"><span class="w"> </span><span class="kd">let</span><span class="w"> </span><span class="n">a</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="fm">vec!</span><span class="p">[</span><span class="mi">1</span><span class="p">,</span><span class="w"> </span><span class="mi">2</span><span class="p">,</span><span class="w"> </span><span class="mi">3</span><span class="p">];</span><span class="w">
+</span></span></span><span class="line"><span class="cl"><span class="w"> </span><span class="kd">let</span><span class="w"> </span><span class="n">b</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="n">a</span><span class="p">;</span><span class="w">
+</span></span></span><span class="line"><span class="cl"><span class="w"> </span><span class="fm">println!</span><span class="p">(</span><span class="s">"</span><span class="si">{:?}</span><span class="s"> </span><span class="si">{:?}</span><span class="s">"</span><span class="p">,</span><span class="w"> </span><span class="n">a</span><span class="p">,</span><span class="w"> </span><span class="n">b</span><span class="p">);</span><span class="w"> </span><span class="c1">// Error; use of moved value: `a`
+</span></span></span><span class="line"><span class="cl"><span class="c1"></span><span class="p">}</span><span class="w">
+</span></span></span></code></pre></div><p>In the above examples, we are just trying to <strong>assign the value of <code>a</code> to <code>b</code></strong> . Almost the same code in both code blocks, but having <strong>two different data types</strong>. And the second one gives an error. This is because of the <strong>Ownership</strong>.</p>Panickinghttps://learning-rust.github.io/docs/panicking/Mon, 01 Jan 0001 00:00:00 +0000https://learning-rust.github.io/docs/panicking/<h2 id="panic">panic!()</h2>
+<ul>
+<li>In some cases, when an error occurs we can not do anything to handle it, <strong>if the error is something which should not have happened</strong>. In other words, if itβs an <strong>unrecoverable error</strong>.</li>
+<li>Also <strong>when we are not using a feature-rich debugger or proper logs</strong>, sometimes we need to <strong>debug the code by quitting the program from a specific line of code</strong> by printing out a specific message or a value of a variable binding to understand the current flow of the program.
+For above cases, we can use <code>panic!</code> macro.</li>
+</ul>
+<p>β <code>panic!()</code> runs <strong>thread based</strong>. One thread can be panicked, while other threads are running.</p>Primitive Data Typeshttps://learning-rust.github.io/docs/primitive-data-types/Mon, 01 Jan 0001 00:00:00 +0000https://learning-rust.github.io/docs/primitive-data-types/<ul>
+<li>
+<h2 id="bool">bool</h2>
+</li>
+</ul>
+<p>true or false</p>
+<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-rust" data-lang="rust"><span class="line"><span class="cl"><span class="kd">let</span><span class="w"> </span><span class="n">x</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="kc">true</span><span class="p">;</span><span class="w">
+</span></span></span><span class="line"><span class="cl"><span class="w"></span><span class="kd">let</span><span class="w"> </span><span class="n">y</span>: <span class="kt">bool</span> <span class="o">=</span><span class="w"> </span><span class="kc">false</span><span class="p">;</span><span class="w">
+</span></span></span><span class="line"><span class="cl"><span class="w">
+</span></span></span><span class="line"><span class="cl"><span class="w"></span><span class="c1">// βοΈ no TRUE, FALSE, 1, 0
+</span></span></span></code></pre></div><ul>
+<li>
+<h2 id="char">char</h2>
+</li>
+</ul>
+<p>A single Unicode scalar value</p>
+<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-rust" data-lang="rust"><span class="line"><span class="cl"><span class="kd">let</span><span class="w"> </span><span class="n">x</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="sc">'x'</span><span class="p">;</span><span class="w">
+</span></span></span><span class="line"><span class="cl"><span class="w"></span><span class="kd">let</span><span class="w"> </span><span class="n">y</span>: <span class="kt">char</span> <span class="o">=</span><span class="w"> </span><span class="sc">'π'</span><span class="p">;</span><span class="w">
+</span></span></span><span class="line"><span class="cl"><span class="w">
+</span></span></span><span class="line"><span class="cl"><span class="w"></span><span class="c1">// βοΈ no "x", only single quotes
+</span></span></span></code></pre></div><p>Because of Unicode support, char is not a single byte, but four(32 bits).</p>
+<ul>
+<li>
+<h2 id="i8-i16-i32-i64-i128">i8, i16, i32, i64, i128</h2>
+</li>
+</ul>
+<p>8, 16, 32, 64 and 128 bit fixed sized signed(+/-) integer types</p>Smart Compilerhttps://learning-rust.github.io/docs/smart-compiler/Mon, 01 Jan 0001 00:00:00 +0000https://learning-rust.github.io/docs/smart-compiler/<h2 id="why-compiler">Why Compiler?</h2>
+<p>The Rust compiler does the most significant job to prevent errors in Rust programs. It <strong>analyzes the code at compile-time</strong> and issues warnings, if the code does not follow memory management rules or lifetime annotations correctly.</p>
+<p>For example,</p>
+<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-rust" data-lang="rust"><span class="line"><span class="cl"><span class="cp">#[allow(unused_variables)]</span><span class="w"> </span><span class="c1">//π‘ A lint attribute used to suppress the warning; unused variable: `b`
+</span></span></span><span class="line"><span class="cl"><span class="c1"></span><span class="k">fn</span> <span class="nf">main</span><span class="p">()</span><span class="w"> </span><span class="p">{</span><span class="w">
+</span></span></span><span class="line"><span class="cl"><span class="w"> </span><span class="kd">let</span><span class="w"> </span><span class="n">a</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="fm">vec!</span><span class="p">[</span><span class="mi">1</span><span class="p">,</span><span class="w"> </span><span class="mi">2</span><span class="p">,</span><span class="w"> </span><span class="mi">3</span><span class="p">];</span><span class="w">
+</span></span></span><span class="line"><span class="cl"><span class="w"> </span><span class="kd">let</span><span class="w"> </span><span class="n">b</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="n">a</span><span class="p">;</span><span class="w">
+</span></span></span><span class="line"><span class="cl"><span class="w">
+</span></span></span><span class="line"><span class="cl"><span class="w"> </span><span class="fm">println!</span><span class="p">(</span><span class="s">"</span><span class="si">{:?}</span><span class="s">"</span><span class="p">,</span><span class="w"> </span><span class="n">a</span><span class="p">);</span><span class="w">
+</span></span></span><span class="line"><span class="cl"><span class="w"></span><span class="p">}</span><span class="w">
+</span></span></span><span class="line"><span class="cl"><span class="w">
+</span></span></span><span class="line"><span class="cl"><span class="w">
+</span></span></span><span class="line"><span class="cl"><span class="w"></span><span class="c1">// ------ Compile-time error ------
+</span></span></span><span class="line"><span class="cl"><span class="c1"></span><span class="n">error</span><span class="p">[</span><span class="n">E0382</span><span class="p">]</span>: <span class="nc">use</span><span class="w"> </span><span class="n">of</span><span class="w"> </span><span class="n">moved</span><span class="w"> </span><span class="n">value</span>: <span class="err">`</span><span class="n">a</span><span class="err">`</span><span class="w">
+</span></span></span><span class="line"><span class="cl"><span class="w"> </span><span class="o">-</span>-> <span class="nc">src</span><span class="o">/</span><span class="n">main</span><span class="p">.</span><span class="n">rs</span>:<span class="mi">6</span>:<span class="mi">22</span><span class="w">
+</span></span></span><span class="line"><span class="cl"><span class="w"> </span><span class="o">|</span><span class="w">
+</span></span></span><span class="line"><span class="cl"><span class="w"></span><span class="mi">3</span><span class="w"> </span><span class="o">|</span><span class="w"> </span><span class="kd">let</span><span class="w"> </span><span class="n">b</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="n">a</span><span class="p">;</span><span class="w">
+</span></span></span><span class="line"><span class="cl"><span class="w"> </span><span class="o">|</span><span class="w"> </span><span class="o">-</span><span class="w"> </span><span class="n">value</span><span class="w"> </span><span class="n">moved</span><span class="w"> </span><span class="n">here</span><span class="w">
+</span></span></span><span class="line"><span class="cl"><span class="w"></span><span class="mi">4</span><span class="w"> </span><span class="o">|</span><span class="w">
+</span></span></span><span class="line"><span class="cl"><span class="w"></span><span class="mi">5</span><span class="w"> </span><span class="o">|</span><span class="w"> </span><span class="fm">println!</span><span class="p">(</span><span class="s">"</span><span class="si">{:?}</span><span class="s">"</span><span class="p">,</span><span class="w"> </span><span class="n">a</span><span class="p">);</span><span class="w">
+</span></span></span><span class="line"><span class="cl"><span class="w"> </span><span class="o">|</span><span class="w"> </span><span class="o">^</span><span class="w"> </span><span class="n">value</span><span class="w"> </span><span class="n">used</span><span class="w"> </span><span class="n">here</span><span class="w"> </span><span class="n">after</span><span class="w"> </span><span class="k">move</span><span class="w">
+</span></span></span><span class="line"><span class="cl"><span class="w"> </span><span class="o">|</span><span class="w">
+</span></span></span><span class="line"><span class="cl"><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="n">note</span>: <span class="nc">move</span><span class="w"> </span><span class="n">occurs</span><span class="w"> </span><span class="n">because</span><span class="w"> </span><span class="err">`</span><span class="n">a</span><span class="err">`</span><span class="w"> </span><span class="n">has</span><span class="w"> </span><span class="k">type</span> <span class="err">`</span><span class="n">std</span>::<span class="n">vec</span>::<span class="nb">Vec</span><span class="o"><</span><span class="kt">i32</span><span class="o">></span><span class="err">`</span><span class="p">,</span><span class="w"> </span><span class="n">which</span><span class="w"> </span><span class="n">does</span><span class="w"> </span><span class="n">not</span><span class="w"> </span><span class="n">implement</span><span class="w"> </span><span class="n">the</span><span class="w"> </span><span class="err">`</span><span class="nb">Copy</span><span class="err">`</span><span class="w"> </span><span class="k">trait</span><span class="w">
+</span></span></span><span class="line"><span class="cl"><span class="w">
+</span></span></span><span class="line"><span class="cl"><span class="w"></span><span class="n">error</span>: <span class="nc">aborting</span><span class="w"> </span><span class="n">due</span><span class="w"> </span><span class="n">to</span><span class="w"> </span><span class="n">previous</span><span class="w"> </span><span class="n">error</span><span class="w">
+</span></span></span><span class="line"><span class="cl"><span class="w"></span><span class="n">For</span><span class="w"> </span><span class="n">more</span><span class="w"> </span><span class="n">information</span><span class="w"> </span><span class="n">about</span><span class="w"> </span><span class="n">this</span><span class="w"> </span><span class="n">error</span><span class="p">,</span><span class="w"> </span><span class="kr">try</span><span class="w"> </span><span class="err">`</span><span class="n">rustc</span><span class="w"> </span><span class="o">--</span><span class="n">explain</span><span class="w"> </span><span class="n">E0382</span><span class="err">`</span><span class="p">.</span><span class="w">
+</span></span></span><span class="line"><span class="cl"><span class="w">
+</span></span></span><span class="line"><span class="cl"><span class="w"></span><span class="c1">// β instead using #[allow(unused_variables)], consider using "let _b = a;" in line 4.
+</span></span></span><span class="line"><span class="cl"><span class="c1">// Also you can use "let _ =" to completely ignore return values
+</span></span></span></code></pre></div><blockquote>
+<p>π In the previous sections, we have discussed memory management concepts like <a href="https://learning-rust.github.io/docs/ownership" >ownership</a>, <a href="https://learning-rust.github.io/docs/borrowing" >borrowing</a>, <a href="https://learning-rust.github.io/docs/lifetimes" >lifetimes</a> and etc.</p>STD, Primitives and Preludeshttps://learning-rust.github.io/docs/std-primitives-and-preludes/Mon, 01 Jan 0001 00:00:00 +0000https://learning-rust.github.io/docs/std-primitives-and-preludes/<p>βοΈ In Rust, language elements are implemented by not only <strong><code>std</code> library</strong> crate but also <strong>compiler</strong> as well. Examples,</p>
+<ul>
+<li><strong><a href="https://doc.rust-lang.org/std/#primitives" target="_blank" >Primitives</a></strong>: Defined by the compiler and methods are implemented by <code>std</code> library directly on primitives.</li>
+<li><strong><a href="https://doc.rust-lang.org/std/#macros" target="_blank" >Standard Macros</a></strong>: Defined by both compiler and <code>std</code></li>
+</ul>
+<p>The <strong><code>std</code></strong> library has been divided into <strong><a href="https://doc.rust-lang.org/std/#modules" target="_blank" >modules</a></strong>, according to the main areas each covered.</p>
+<p>βοΈ While primitives are implemented by the <strong>compiler</strong>, the standard library implements the <strong>most useful methods</strong> directly on the primitive types. But some <strong>rarely useful language elements</strong> of some primitives are stored on relevant <strong><code>std</code> modules</strong>. This is why you can see <code>char</code>, <code>str</code> and integer types on both <a href="https://doc.rust-lang.org/std/#primitives" target="_blank" >primitives</a> and <a href="https://doc.rust-lang.org/std/#modules" target="_blank" ><code>std</code> modules</a>.</p>Structshttps://learning-rust.github.io/docs/structs/Mon, 01 Jan 0001 00:00:00 +0000https://learning-rust.github.io/docs/structs/<p>βοΈ Structs are used to <strong>encapsulate related properties</strong> into one unified data type.</p>
+<p>π‘ By convention, the name of the struct should follow <a href="https://en.wikipedia.org/wiki/Camel_case" target="_blank" >PascalCase</a>.</p>
+<p>There are 3 variants of structs,</p>
+<ol>
+<li><strong>C-like structs</strong></li>
+</ol>
+<ul>
+<li>One or more comma-separated name:value pairs</li>
+<li>Brace-enclosed list</li>
+<li>Similar to classes (without its methods) in OOP languages</li>
+<li>Because fields have names, we can access them through dot notation</li>
+</ul>
+<ol start="2">
+<li><strong>Tuple structs</strong></li>
+</ol>
+<ul>
+<li>One or more comma-separated values</li>
+<li>A parenthesized list like tuples</li>
+<li>Looks like a named tuples</li>
+</ul>
+<ol start="3">
+<li><strong>Unit structs</strong></li>
+</ol>
+<ul>
+<li>A struct with no members at all</li>
+<li>It defines a new type but it resembles an empty tuple, ()</li>
+<li>Rarely in use, useful with generics</li>
+</ul>
+<p>βοΈ When regarding OOP in Rust, attributes and methods are placed separately on <strong>structs</strong> and <strong>traits</strong>. Structs contain only attributes, traits contain only methods. They are getting connected via <strong>impls</strong>.</p>Unwrap and Expecthttps://learning-rust.github.io/docs/unwrap-and-expect/Mon, 01 Jan 0001 00:00:00 +0000https://learning-rust.github.io/docs/unwrap-and-expect/<h2 id="unwrap">unwrap()</h2>
+<ul>
+<li>If an <code>Option</code> type has <strong><code>Some</code></strong> value or a <code>Result</code> type has a <strong><code>Ok</code></strong> value, <strong>the value inside them</strong> passes to the next step.</li>
+<li>If the <code>Option</code> type has <strong><code>None</code></strong> value or the <code>Result</code> type has <strong><code>Err</code></strong> value, <strong>program panics</strong>; If <code>Err</code>, panics with the error message.</li>
+</ul>
+<p>The functionality is bit similar to the following codes, which are using <code>match</code> instead <code>unwrap()</code>.</p>
+<p>Example with <code>Option</code> and <code>match</code>, before using <code>unwrap()</code></p>Usehttps://learning-rust.github.io/docs/use/Mon, 01 Jan 0001 00:00:00 +0000https://learning-rust.github.io/docs/use/<p>Let’s see the main usages of the <code>use</code> keyword.</p>
+<h2 id="01-bind-a-full-path-to-a-new-name">01. Bind a full path to a new name</h2>
+<p>Mainly <code>use</code> keyword is used to bind a full path of an element to a new name. So the user doesnβt want to repeat the full path each time.</p>
+<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-rust" data-lang="rust"><span class="line"><span class="cl"><span class="c1">// -- Initial code without the `use` keyword --
+</span></span></span><span class="line"><span class="cl"><span class="c1"></span><span class="k">mod</span> <span class="nn">phrases</span><span class="w"> </span><span class="p">{</span><span class="w">
+</span></span></span><span class="line"><span class="cl"><span class="w"> </span><span class="k">pub</span><span class="w"> </span><span class="k">mod</span> <span class="nn">greetings</span><span class="w"> </span><span class="p">{</span><span class="w">
+</span></span></span><span class="line"><span class="cl"><span class="w"> </span><span class="k">pub</span><span class="w"> </span><span class="k">fn</span> <span class="nf">hello</span><span class="p">()</span><span class="w"> </span><span class="p">{</span><span class="w">
+</span></span></span><span class="line"><span class="cl"><span class="w"> </span><span class="fm">println!</span><span class="p">(</span><span class="s">"Hello, world!"</span><span class="p">);</span><span class="w">
+</span></span></span><span class="line"><span class="cl"><span class="w"> </span><span class="p">}</span><span class="w">
+</span></span></span><span class="line"><span class="cl"><span class="w"> </span><span class="p">}</span><span class="w">
+</span></span></span><span class="line"><span class="cl"><span class="w"></span><span class="p">}</span><span class="w">
+</span></span></span><span class="line"><span class="cl"><span class="w">
+</span></span></span><span class="line"><span class="cl"><span class="w"></span><span class="k">fn</span> <span class="nf">main</span><span class="p">()</span><span class="w"> </span><span class="p">{</span><span class="w">
+</span></span></span><span class="line"><span class="cl"><span class="w"> </span><span class="n">phrases</span>::<span class="n">greetings</span>::<span class="n">hello</span><span class="p">();</span><span class="w"> </span><span class="c1">// Using full path
+</span></span></span><span class="line"><span class="cl"><span class="c1"></span><span class="p">}</span><span class="w">
+</span></span></span><span class="line"><span class="cl"><span class="w">
+</span></span></span><span class="line"><span class="cl"><span class="w">
+</span></span></span><span class="line"><span class="cl"><span class="w"></span><span class="c1">// -- Usage of the `use` keyword --
+</span></span></span><span class="line"><span class="cl"><span class="c1">// 01. Create an alias for module
+</span></span></span><span class="line"><span class="cl"><span class="c1"></span><span class="k">use</span><span class="w"> </span><span class="n">phrases</span>::<span class="n">greetings</span><span class="p">;</span><span class="w">
+</span></span></span><span class="line"><span class="cl"><span class="w"></span><span class="k">fn</span> <span class="nf">main</span><span class="p">()</span><span class="w"> </span><span class="p">{</span><span class="w">
+</span></span></span><span class="line"><span class="cl"><span class="w"> </span><span class="n">greetings</span>::<span class="n">hello</span><span class="p">();</span><span class="w">
+</span></span></span><span class="line"><span class="cl"><span class="w"></span><span class="p">}</span><span class="w">
+</span></span></span><span class="line"><span class="cl"><span class="w">
+</span></span></span><span class="line"><span class="cl"><span class="w"></span><span class="c1">// 02. Create an alias for module elements
+</span></span></span><span class="line"><span class="cl"><span class="c1"></span><span class="k">use</span><span class="w"> </span><span class="n">phrases</span>::<span class="n">greetings</span>::<span class="n">hello</span><span class="p">;</span><span class="w">
+</span></span></span><span class="line"><span class="cl"><span class="w"></span><span class="k">fn</span> <span class="nf">main</span><span class="p">()</span><span class="w"> </span><span class="p">{</span><span class="w">
+</span></span></span><span class="line"><span class="cl"><span class="w"> </span><span class="n">hello</span><span class="p">();</span><span class="w">
+</span></span></span><span class="line"><span class="cl"><span class="w"></span><span class="p">}</span><span class="w">
+</span></span></span><span class="line"><span class="cl"><span class="w">
+</span></span></span><span class="line"><span class="cl"><span class="w"></span><span class="c1">// 03. Customize names with the `as` keyword
+</span></span></span><span class="line"><span class="cl"><span class="c1"></span><span class="k">use</span><span class="w"> </span><span class="n">phrases</span>::<span class="n">greetings</span>::<span class="n">hello</span><span class="w"> </span><span class="k">as</span><span class="w"> </span><span class="n">greet</span><span class="p">;</span><span class="w">
+</span></span></span><span class="line"><span class="cl"><span class="w"></span><span class="k">fn</span> <span class="nf">main</span><span class="p">()</span><span class="w"> </span><span class="p">{</span><span class="w">
+</span></span></span><span class="line"><span class="cl"><span class="w"> </span><span class="n">greet</span><span class="p">();</span><span class="w">
+</span></span></span><span class="line"><span class="cl"><span class="w"></span><span class="p">}</span><span class="w">
+</span></span></span></code></pre></div><h2 id="02-import-elements-to-scope">02. Import elements to scope</h2>
+<p>Another common usage of <code>use</code> is importing elements to scope. Remember that, this is also a bit similar to creating an alias and using it instead of using the full path.</p>Variable bindings, Constants & Staticshttps://learning-rust.github.io/docs/variable-bindings-constants-and-statics/Mon, 01 Jan 0001 00:00:00 +0000https://learning-rust.github.io/docs/variable-bindings-constants-and-statics/<h2 id="variable-bindings-constants--statics">Variable bindings, Constants & Statics</h2>
+<p>βοΈ In Rust, variables are <strong>immutable by default</strong>, so we call them <strong>Variable bindings</strong>. To make them mutable, the <code>mut</code> keyword is used.</p>
+<p>βοΈ Rust is a <strong>statically typed</strong> language; it checks data types at compile-time. But it <strong>doesnβt require you to actually type it when declaring variable bindings</strong>. In that case, the compiler checks the usage and sets a better data type for it. But for <strong>constants and statics, you must annotate the type</strong>. Types come after a colon(<code>:</code>).</p>Vectorshttps://learning-rust.github.io/docs/vectors/Mon, 01 Jan 0001 00:00:00 +0000https://learning-rust.github.io/docs/vectors/<p>If you remember, the array is a fixed-size list of elements, of the same data type. Even with mut, its element count cannot be changed. A vector is kind of <strong>a re-sizable array</strong> but <strong>all elements must be in the same type</strong>.</p>
+<p>βοΈ Itβs a generic type, written as <strong><code>Vec<T></code></strong>Β . T can have any type, ex. The type of a Vec of i32s is <code>Vec<i32></code>. Also, Vectors always allocate their data in a dynamically allocated heap.</p>Why Rust?https://learning-rust.github.io/docs/why-rust/Mon, 01 Jan 0001 00:00:00 +0000https://learning-rust.github.io/docs/why-rust/<h2 id="history-of-rust">History of Rust</h2>
+<p>Rust was initially designed and developed by former Mozilla employee <strong><a href="https://github.com/graydon" target="_blank" >Graydon Hoare</a></strong> as a personal project. Mozilla began sponsoring the project in 2009 and announced it in 2010. But the first stable release, Rust 1.0, was released on May 15, 2015.</p>
+<p>Since Rust 1.0, major updates have been released as <a href="https://learning-rust.github.io/docs/cargo-crates-and-basic-project-structure/#rust-editions" ><code>Editions</code></a> approximately every three years: Rust 2015 (with the release of Rust 1.0) , Rust 2018, Rust 2021, and Rust 2024, all maintaining backward compatibility.</p>Workspaceshttps://learning-rust.github.io/docs/workspaces/Mon, 01 Jan 0001 00:00:00 +0000https://learning-rust.github.io/docs/workspaces/<p>When the code base is getting larger, you might need to work with <strong>multiple crates on the same project</strong>. Rust supports this via Workspaces. You can <strong>analyze (<code>cargo check</code>), build, run tests or generate docs for all crates</strong> at once by running <code>cargo</code> commands from the project root.</p>
+<p>βοΈ When working on multiple crates same time, there is a higher possibility of having shared dependencies on crates. To prevent downloading and compiling the same dependency multiple times, Rust uses a <strong>shared build directory</strong> under the project root, while running <code>cargo build</code> from the project root.</p>
\ No newline at end of file
diff --git a/docs/manifest.json b/docs/manifest.json
new file mode 100644
index 0000000..87493f4
--- /dev/null
+++ b/docs/manifest.json
@@ -0,0 +1,21 @@
+{
+ "name": "Learning Rust",
+ "short_name": "Learning Rust",
+ "description": "Rust Programming Language Tutorials for Everyone!",
+ "start_url": "/?source=pwa",
+ "display": "standalone",
+ "icons": [
+ {
+ "src": "/favicon/android-chrome-192x192.png",
+ "sizes": "192x192",
+ "type": "image/png"
+ },
+ {
+ "src": "/favicon/android-chrome-512x512.png",
+ "sizes": "512x512",
+ "type": "image/png"
+ }
+ ],
+ "background_color": "#866ee7",
+ "theme_color": "#866ee7"
+}
\ No newline at end of file
diff --git a/docs/sitemap.xml b/docs/sitemap.xml
new file mode 100644
index 0000000..e76015b
--- /dev/null
+++ b/docs/sitemap.xml
@@ -0,0 +1 @@
+https://learning-rust.github.io/docs/borrowing/2022-10-17T01:47:29+08:00https://learning-rust.github.io/docs/cargo-crates-and-basic-project-structure/2025-03-13T18:13:30+08:00https://learning-rust.github.io/categories/https://learning-rust.github.io/docs/code-organization/2022-10-22T16:55:03+08:00https://learning-rust.github.io/docs/combinators/2023-11-11T20:38:50+08:00https://learning-rust.github.io/docs/comments-and-documenting-the-code/2023-11-11T20:38:50+08:00https://learning-rust.github.io/docs/control-flows/2024-02-01T23:03:34+05:30https://learning-rust.github.io/docs/crates/2022-10-17T01:47:29+08:00https://learning-rust.github.io/docs/custom-error-types/2023-11-11T20:38:50+08:00https://learning-rust.github.io/docs/2025-03-13T18:22:59+08:00https://learning-rust.github.io/docs/enums/2022-10-17T01:47:29+08:00https://learning-rust.github.io/docs/error-and-none-propagation/2023-11-11T20:38:50+08:00https://learning-rust.github.io/docs/functions/2023-11-11T20:38:50+08:00https://learning-rust.github.io/docs/functions-02/2022-10-17T01:47:29+08:00https://learning-rust.github.io/docs/generics/2022-10-22T16:55:03+08:00https://learning-rust.github.io/docs/hello-world/2024-03-10T20:15:12+08:00https://learning-rust.github.io/docs/impls-and-traits/2024-02-02T01:29:34+09:00https://learning-rust.github.io/docs/installation/2025-03-13T18:22:59+08:00https://learning-rust.github.io/2025-03-13T18:22:59+08:00https://learning-rust.github.io/docs/lifetimes/2022-10-17T01:47:29+08:00https://learning-rust.github.io/docs/modules/2022-10-17T01:47:29+08:00https://learning-rust.github.io/docs/operators/2023-11-11T20:38:50+08:00https://learning-rust.github.io/docs/option-and-result/2024-02-01T19:02:07+01:00https://learning-rust.github.io/docs/overview/2024-03-10T20:15:12+08:00https://learning-rust.github.io/docs/ownership/2022-10-17T01:47:29+08:00https://learning-rust.github.io/docs/panicking/2023-11-11T20:38:50+08:00https://learning-rust.github.io/docs/primitive-data-types/2023-11-11T20:38:50+08:00https://learning-rust.github.io/docs/smart-compiler/2023-11-11T20:38:50+08:00https://learning-rust.github.io/docs/std-primitives-and-preludes/2022-10-17T01:47:29+08:00https://learning-rust.github.io/docs/structs/2023-11-11T20:38:50+08:00https://learning-rust.github.io/tags/https://learning-rust.github.io/docs/unwrap-and-expect/2023-11-11T20:38:50+08:00https://learning-rust.github.io/docs/use/2022-10-17T01:47:29+08:00https://learning-rust.github.io/docs/variable-bindings-constants-and-statics/2023-11-11T20:38:50+08:00https://learning-rust.github.io/docs/vectors/2022-10-22T16:55:03+08:00https://learning-rust.github.io/docs/why-rust/2025-03-13T17:11:45+08:00https://learning-rust.github.io/docs/workspaces/2022-10-17T01:47:29+08:00
\ No newline at end of file
diff --git a/docs/sw.js b/docs/sw.js
new file mode 100644
index 0000000..9c27f9f
--- /dev/null
+++ b/docs/sw.js
@@ -0,0 +1,56 @@
+const cacheName = 'learning-rust-{{ now.Format "2006-01-02" }}';
+const staticAssets = [
+ './',
+ './index.html',
+ './manifest.json',
+ './docs/**/*',
+ './favicon/android-chrome-192x192.png',
+ './favicon/android-chrome-512x512.png',
+ './favicon/apple-touch-icon.png',
+ './favicon/favicon.ico',
+ './favicon/favicon-16x16.png',
+ './favicon/favicon-32x32.png',
+ './css/home.min.*.css',
+ './css/docs.min.*.css',
+ './js/home.min.*.js',
+ './js/docs.min.*.js',
+];
+
+self.addEventListener('install', async e => {
+ const cache = await caches.open(cacheName);
+ await cache.addAll(staticAssets);
+ return self.skipWaiting();
+});
+
+self.addEventListener('activate', e => {
+ self.clients.claim();
+});
+
+self.addEventListener('fetch', async e => {
+ const req = e.request;
+ const url = new URL(req.url);
+
+ if (url.origin === location.origin) {
+ e.respondWith(cacheFirst(req));
+ } else {
+ e.respondWith(networkFirst(req));
+ }
+});
+
+async function cacheFirst(req) {
+ const cache = await caches.open(cacheName);
+ const cached = await cache.match(req);
+ return cached || fetch(req);
+}
+
+async function networkFirst(req) {
+ const cache = await caches.open(cacheName);
+ try {
+ const fresh = await fetch(req);
+ cache.put(req, fresh.clone());
+ return fresh;
+ } catch (e) {
+ const cached = await cache.match(req);
+ return cached;
+ }
+}
\ No newline at end of file
diff --git a/docs/tags/index.xml b/docs/tags/index.xml
new file mode 100644
index 0000000..6e03319
--- /dev/null
+++ b/docs/tags/index.xml
@@ -0,0 +1 @@
+Tags on Learning Rusthttps://learning-rust.github.io/tags/Recent content in Tags on Learning RustHugoen-US
\ No newline at end of file