Key points to get started with Rust < Part 1 >

Pros

  • Dangling Pointers

  • Buffer overflow

  • Updating Iterators in a loop

  • Avoiding race condition

Cons

  • Type Strictness

  • Edge cases

  • Cyclic DS

  • Compile Time

  • Standard lib has less feature, cargo ftw!

Number Data Type

  • Numbers have methods attached to them. Eg: 3.pow(2)

  • Promotion is better, u8 as i32 instead of i32 as u8

  • Never compare floating points. It's better to use delta (EPSILON) to check.

  • Floats are partially equated.

  • 0b, 0o, 0X - Binary, Octal, Hexadecimal

  • NAN - undefined mathematical values (NAN != NAN)

  • Use is_nan and is_finite to check.

  • Use Fixed point decimal for currencies.

Flow Control

  • & - for reference

  • Range

    • Exclusive - (n..m)

    • Inclusive - (n..=m)

  • Anonymous Loop - for _ in 0..10 {

  • Avoid managing an index variable (collection[i]) X

    • Performance & Safety is compromised.
  • loop - For infinite looping till break keyword is encountered.

    • break can also return value. E.g., break 253.
  • Break from nested loops with loop labels (').

  • Expression based language

  • Not expression

    • Assignment operator (=)

    • Type declaration (fn, struct, enum)

  • () - No value.

Match

  • Exact value, range (0..10), or (10 | 20), _ (all values).

  • You need to provide for each case otherwise compile-time error.

Reference

  • & - ref

  • * - Deref

Lifetime

  • <‘a, ‘b> - Read as lifetime ‘a, lifetime ‘b.

  • Lifetime is implicit most of the time and done by the compiler.

  • Specify lifetime explicitly when multiple references are arguments or return a reference.

Strings

  • Multiline strings do not need special syntax.

  • Two types (String and &str).

  • Better to convert to String type.

  • String (similar to other programming languages)

    • Concatenation

    • Adding new strings

    • Removing whitespace

    • Dynamic

    • Read Write

  • &str (string slice)

    • Fixed raw type array

    • No dynamic memory allocation

    • Read only

    • Static type (&’static str)

Static Memory

  • char

  • [u8] - Good for reading string directly from a file

  • Vec<u8>

Array

  • [0; 100] - Repeat expression

  • [u8; 3] != [u8, 4]

Slices

  • Dynamically sized array-like objects.

  • [T] - they don't grow or reduce.

  • Easier to create Traits compared to an array.

Vectors

  • Dynamic arrays (grow and shrink).

  • Best to initialize with with_capacity().

Files

  • Use BufReader to reduce hard disk congestion

  • Use from_utf8_lossy to replace any byte which is not UTF-8 with "?"

Debugging

  • Use {:?} to print data structure for debugging

  • Use cfg!(assertion) to execute certain functions in non-release builds

  • Use #![allow(<exception>)] to help with compiler warnings during development

  • Exceptions include:

    • unused_variables

    • dead_code

  • Use #[derive(Debug)] to support {:?}

Methods

  • Only use unwrap when you are sure it won't give an error

Returns

  • ! represents the never type, indicating that the function never returns (e.g. infinite loop inside a function)

  • () represents the unit type, indicating that there is no return value

  • Understand the difference between the above points

Macros

  • unimplemented!() crashes the code if encountered

  • panic!("") crashes the code

Types

  • Aliasing makes sure that all methods are available for the declared type

  • <_> - Lets rust infer type

Struct

  • Struct is a composite data structure, similar to an object

  • Methods (impl) do not require the main object to be passed

  • Use new() to initialize structs instead of the normal way. It is not a keyword and needs to be defined.

  • Fields are private by default and can only be accessed if defined in the same scope

New Type Pattern

  • Wrapping a core type in a single field struct or tuple.

Static Data Types - Global Variable

  • static mut - Global variable with lifetime that’s valid for life of the program

  • unsafe { } - To be used to access and modify static mut variables

  • Convention to use CAPS while naming

  • const - For values that never change

let vs const -

  • let - has inner mutability that means aliasing ( multiple references )

  • const - immutable

Enum -

  • Used to cover all the edge cases

  • Result

    • Ok

    • Err

  • Using unwrap with Result Enum is bad practice

  • Enum can take value Enum_Name(Value)

Scope

  • Private scope as default

  • “pub” to make scope public

Traits

  • Enable code reuse

  • Allows compiler to perform zero cost abstraction

  • PartialEq - 2 values which matches equally should not be treated equal

  • trail <TRAIT_NAME>

  • impl <TRAIT_NAME> for <STRUCT/ENUM_NAME>

Misc

  • cargo doc creates HTML documentation

  • cargo add <lib>

  • cargo install cargo-edit

  • rustup doc

  • /// - Generate doc for immediate item

  • //! - For compiler to print which module is being run

  • rustdoc <file_name> creates documentation using ( /// )

Borrowing and Ownership < Part 2 >


PS:

  • Will keep updating the page as I learn and discover more about Rust

  • Do check out "Rust in Action" by Tim McNamara", a great book and my primary source of learning!