Skip to content

sahilrajput03/learning_rust

Repository files navigation

Readme

LAST UPDATE: Continue doing rustlings/exercies/errors-handling/README.md (it has links which I read last). Learning how to handle errors is really awesome, i.e.,

  • in errors2.rs test I learned that with return value as Result<i32, &str> I am saying that i can return two values i.e., Ok(i32) or Err("a string slice").

  • in errors3.rs test I learned that I must return a Result<a,b> type from the main() function so that I can use ?, which is basically does like "stop the function in runtime when an error is caused".

  • in errors4.rs test I learned that I can define an enum like

enum CreationError {
	is_negative,
	is_zero,
}

which help me to define like return type as Result<a,CreationError> so that means I can make use of different types of error by defining the return type for error as CreationError as Result<a, CreationError>.

  • in errors5.rs test I learned that I can make use of somthing like Result<(), Box<dyn error::Error>> so that I can make a explicit list of error which aren't catchable distinguishly but on a general basis i.e., any Err(..) can be returned for which I have implemented error:Error. Yo!! This can be hacky way to catch a list of errors my adding error::Error implementations to them and making those errors compatible with the compiler but it isn't good for library coz we need to get what exact error is thrown in each case which is not possible with Result<a,CreationError>.

  • in errors6.rs test I learned that I can remodel any error to anything with a functional approach that is so awesome and feels like fucntional approach is good way to simply map the error to our own error made up instances, e.g., (from docs).

    // LEARN: from docs of map_err:: ~Sahil
    //
    // fn stringify(x: u32) -> String { format!("error code: {}", x) }
    
    // let x: Result<u32, u32> = Ok(2);
    // assert_eq!(x.map_err(stringify), Ok(2));
    
    // let x: Result<u32, u32> = Err(13);
    // assert_eq!(x.map_err(stringify), Err("error code: 13".to_string()));
    

Try out:

IMPORTANT: Attributes can be crate level (i.e., once for the complete file ~Sahil) or it can be particular to a struct, module, function, etc.

You can either:

Source: https://stackoverflow.com/a/25877389/10012446

  • Add an allow attribute on a struct, module, function, etc.:
#[allow(dead_code)]
struct SemanticDirection;
// So dead_code attibute will only apply to this struct only.
  • Add a crate-level allow attribute; notice the !: #![allow(dead_code, unused)]

FYI:: allow(unused) will supress all nested warning as well like: allow(unused_mut, unused_variables, ... and many more..).

  • Pass it to rustc: rustc -A dead_code main.rs

  • Pass it using cargo via the RUSTFLAGS environment variable: RUSTFLAGS="$RUSTFLAGS -A dead_code" cargo build

Creating new project:

cargo init --bin my-project
# or
cargo init --lib my-library

more -> global installs

cargo install cargo-edit

# Usage:
cargo add pkg-name1 pkg-name2 ... # It wil add latest version of package with its version to your cargo.toml file automatically.
cargo install cargo-whatfeatures

# Usage:
cargo whatfeatures package-name-here # Shows you the available features from a package.
  • cargo install docs:
cargo install [options] crate...
cargo install [options] --path path
cargo install [options] --git url [crate...] # This one is useful!
cargo install [options] --list

# FYI: ~sahil i used it to do:
cargo install --git https://github.com/davidpdrsn/cargo-docserver

a static http files server with rust: https://github.com/DenisKolodin/static-server

tokio is most trusted and used web framework in rust

todo:

Rust's blog: here

Rust 2020 survey result here.

Do check if 2021 survey result is launched or not...

mongodb resources

Official Mongodb Driver for rust, Mongo rust driver@Github

Google - Search - Mongodb for rust

Learn rust - https://www.rust-lang.org/learn

IMPORTANT >> NOW <<>> > << >>

Continue book rust programming with example from pg. 129.

Install cargo-watch to watch over a project

Cargo installs all binaries to ~/.cargo/bin directory as state in docs here. Install: ls ~/.cargo/bin/

Crate: https://crates.io/crates/cargo-watch, Docs: https://docs.rs/crate/cargo-watch/7.0.2

Usage:

#Watch for ``cargo run``
$ cargo watch -x run
$ cargo-watch -x run # Notice the dash between cargo and watch.
$ cw # My personal alias for cargo watch i.e., ```cargo watch -x run```

#Watch for ``cargo check``
$ cargo watch # Default: `cargo check` i.e: cargo watch -x check

# PRO TIP:
cargo watch -q -c -x run
# Here -c or --clear clears the output before each run.
# -q or --quiet hides the output.
#Look for more command in Crate docs.

## MY PERSONAL ALIASES FROM .bashrc file:
alias cw='cargo watch -q -c -x "run -q"'
#cargo watch --quiet --clear --exec 'run --quiet'

Primitive types

https://doc.rust-lang.org/std/index.html#primitives

Data types - Chapter in officila book: https://doc.rust-lang.org/book/ch03-02-data-types.html#integer-types

isize and usize:

The isize and usize types depend on the kind of computer your program is running on: 64 bits if you’re on a 64-bit architecture and 32 bits if you’re on a 32-bit architecture.

Operators

https://doc.rust-lang.org/book/appendix-02-operators.html#operators

signed integer read more here

println! is a macro, what else is macro in rust?

https://doc.rust-lang.org/std/index.html#macros

Official Rust book

https://doc.rust-lang.org/book/

Amazing rustlings game course

https://github.com/rust-lang/rustlings/

Install: Manual Install@RustlingsRepo

SELF NOTES:: Installed in this repo in rustlings folder.

USE rustlings cli tool from the rustlings folder to start the game.

Amazing rust by example book

https://doc.rust-lang.org/stable/rust-by-example/

Another awesome book with name "Rust programming by example ~ Guillaume Gomez and Antoni Boucher"

Comprehensive guide to the Rust standard library APIs.

(amazing glossary of things in rust ~sahil)

https://doc.rust-lang.org/std/index.html

(the standard library)

src: https://www.rust-lang.org/learn

Guide to editions of rust

https://doc.rust-lang.org/edition-guide/index.html

(edition guide)

src: https://www.rust-lang.org/learn

A book on Rust’s package manager and build system - Cargo

https://doc.rust-lang.org/cargo/index.html

(cargo book)

src: https://www.rust-lang.org/learn

Learn how to make awesome documentation for your crate.

https://doc.rust-lang.org/rustdoc/index.html

(rustdoc book)

src: https://www.rust-lang.org/learn

Familiarize yourself with the knobs available in the Rust compiler.

https://doc.rust-lang.org/rustc/index.html

(rustc book)

src: https://www.rust-lang.org/learn

In-depth explanations of the errors you may see from the Rust compiler.

https://doc.rust-lang.org/error-index.html

(compiler error index)

src: https://doc.rust-lang.org/error-index.html

Rust community

https://users.rust-lang.org/

https://t.me/rust_community

Using rustmon

rustmon fileName.rs or rmon fileName.rs

For e.g., let say you have a rust program myprogram.rs then you'd need to run rustmon myprogram.rs from the cli to run it in monitor mode.

Install rust

curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh

src: https://www.rust-lang.org/tools/install

System programming

https://en.wikipedia.org/wiki/Systems_programming

Formatter with vscode on code save

xxx note xxxx

Simply use rust-analyzer and uninstall origianl rust vscode extension

If you have some async code in your project then you must have a rustfmt.toml file in the root of your ANY NESTED project (with content: edition = "2018") to make rust formatter work for that project too otherwise the files won't format at all. UPDATED AT: 4 FEB, 2022.

Thats how tekipeps did, and it feels amazing as now i don't need to Cargo.toml in any opened folder in vscode so vsocode can format the files and rustfmt.toml works as expected!! Yikes!

You can use

LEARN: rustfmt <fileName> to format a file as well.

Also info from rust-analyzer (from its extension):
rust-analyzer
Provides support for rust-analyzer: novel LSP server for the Rust programming language.

Note the extension may cause conflicts with the official Rust extension. It is recommended to disable the Rust extension when using the rust-analyzer extension.

Note the project is in alpha status: it is already useful in practice, but can't be considered stable.

Simply install this extension and make sure that you have a cargo.toml file in the root of folder that you have opened in vscode to make format on save works!

NOT WORKING: >>> Search for setting in vscode like: rust rustfmt_path and add path for your own global rustfmt.toml file. *You must have official rust extension installed to see this setting.

Global rustfmt.toml file location => PR: rust-lang/rustfmt#3280 .

An ideal Cargo.toml file should be place in the root of folder opened in vscode i.e.,

(Bcoz Vscode's rust extension using command cargo fmt --all to format the code and throws error if the Cargo.toml file isn't formatted properly.)

[package]
name = "a-small-rust-app"
version = "0.1.0"

[[bin]]
name = "general"
path = "01_println.rs"

Updating rustc via rustup

rustup update

more..

Tips:

  1. Tutorial here.

0.5. Was here.

  1. Whenever you see something like car::bike::scooter means that car is a module and bike is nested module inside car and scooter is a module nested inside bike.

  2. strings: amazing article, or read from amazing docs :LOL:.

  3. Gitignore.

  4. Primitives.

  5. Reqwest

  6. Rustler thing(popular idk why..): 1. @docs, 2. @github, @crates.io site.

MISSION: → → → → → → finish till vid-42.

**Continue the vid-35 tutorial/and making this gist. @ here

todo: Findout most popular web server from crate.io for rust??

Follow a different course, and it feel good too

Rust important links:

Creating rust projects with cargo (source)

$ cargo new hello-world-cargo --bin  # --bin tells the cargo to create a application project, not a library project.
$ cd hello-world-cargo
$ cargo run # This will output `Hello world!`. Congrats!!
$ `cargorun` or `cw` will run cargo in dev mode just like nodemon does, yikes!

The cargo application has entry point from src/main.rs file. All rust programs begin with a main function.

Firstly, anytime you make changes to src/main.rs, you need to run cargo run from cli. Secondly, cargo.toml file is similar to package.json file, as you'll find project info and dependencies there. Thirdly, you'll get a git initiated project with pre-made .gitignore file.

Compile and run with rustc

// File, main.rs
fn main(){
  println!("Hello world!")
}

Compile rust program via rustc main.rs and run it via ./main (from bash) or main.exe (from command prompt).

--bin
Create a package with a binary target (src/main.rs). This is the default behavior.
--lib
Create a package with a library target (src/lib.rs).

Snippets from the official rust vscode extension

src: https://github.com/rust-lang/vscode-rust#snippets

## Snippets
Snippets are code templates which expand into common boilerplate. IntelliSense includes snippet names as options when you type; select one by pressing enter. You can move to the next snippet 'hole' in the template by pressing tab. We provide the following snippets:

for - a for loop
macro_rules - declare a macro
if let - an if let statement for executing code only when a pattern matches
spawn - spawn a thread
extern crate - insert an extern crate statement
This extension is deliberately conservative about snippets and doesn't include too many. If you want more, check out Trusty Rusty Snippets.

So, fun.. below extension provides many rust snippets and officially recommended from rust vscode extension for snippets.

https://marketplace.visualstudio.com/items?itemName=polypus74.trusty-rusty-snippets

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published