Efficient, secure, performant concurrent systems programming that compiles to machine code
NOTE: Content here are my personal opinions, and not intended to represent any employer (past or present). “PROTIP:” here highlight information I haven’t seen elsewhere on the internet because it is hard-won, little-know but significant facts based on my personal research and experience.
This article, here at https://bomonike.github.io/rustlang, and its companion repo at github.com/bomonike/rustlang-samples, describe the quickest way to use AI to build practical and working computer applications while learning the Rust language.
rust-lang.org is the home page for the language.
The mascot for the Rust language is a red crab?
Its name is Ferris (like “ferrous”)
because ferrous oxide is the chemical name for rust from iron.
Wikipedia notes that the Rust language begun in 2006 as a personal project by Graydon Hoare while an employee of that browser company Mozilla.
In 2013 Graydon Hoare stepped away from the project to join Apple (to work on their Swift language).
2009: Mozilla recognized the potential of Hoare’s project and officially became its sponsor. Graydon was able to work on Rust full-time with a growing team.
Rust was officially announced to the public by Mozilla on
July 7, 2010.
Rust 1.0 was released (under open-source MIT license) ??? on May 15, 2015 as the “official” birth of the language, when it became stable enough for developers to confidently use in production.
REMEMBER: Unlike Python, JavaScript:
Rust maintainers have a 6-week rapid release process even though they support a large number of platforms.
Videos from Rust conf presentations
Rust jobs on Linkedin by Alex Garella in Turkiye
LinkedIn Jobs in Rust (Remote)
Rust uses LLVM to generate a language compiler/debugger, so performance improvements in LLVM would also benefit Rust.
During the pandemic in August 2020, Mozilla laid off most of the Rust team (along with completely disbanding the Servo parallel browser team). The event raised concerns about the future of Rust.
On Feburary 2021, the “Rust Foundation” [Linkedin] was formed with AWS, Huawei, Google, Microsoft, and Mozilla, who all use Rust as a systems programming language:
Linkerd creator Oliver Gould, says the Future of the Cloud will be Built on Rust CNCF
| Feature: | Package | Crate | Module |
| Analogy: | bookshelf (holds everything together) | individual book | Chapters in the book |
| Definition: | a wrapper that contains one or more crates | the root of modules | branches inside that root |
| How many per level? | 1 package per project | 1+ per package | Many per crate |
| What is it? | A distribution unit | A compilation unit | A namespace/organizer |
| Defined by: | Cargo.toml | main.rs or lib.rs | mod keyword or file tree |
| Purpose: | Manage dependencies, build settings, and publishing | Group code that compiles together | Control visibility and scope |
| Example: | cargo new my_app | serde, rand, tokio | std::fs, std::io |
VIDEO:
In the “src” folder along with main.rs there can be a module such as “bank.rs”.
The first line within bank.rs would be “mod bank”.
Alternately, that code can be in a mod.rs under a folder named “bank”.
In the “src” folder along with main.rs a module called “lib.rs” contain functions that can be accessed by several modules.
Rust was rated the “most loved” among all programming languages in the 2020 StackOverflow survey of developers (ahead of Python, TypeScript, Kotlin, etc.).
“In other languages simple things are easy and complex things are possible, in Rust simple things are possible and complex things are easy.”
Rust was #26 on the TIOBE index of programming languages, based on “the number of skilled engineers world-wide, courses and third party vendors. Popular search engines such as Google, Bing, Yahoo!, Wikipedia, Amazon, YouTube and Baidu were used to calculate the ratings.”.
Like C, C++, Java:
REMEMBER: VIDEO: The genius of Rust is that its memory “borrowing” and “ownership” model provides a way to avoid much of the null pointer exceptions and buffer overrun issues in C and garbage collection delays in Java.
“Rust isn’t difficult. It’s unfamiliar.”
“Rust enables low-level control without giving up high-level conveniences.”
Rust is used to write performance intensive, highly-concurrent code, with predictable tail latencies. Thus, Rust can power performance-critical services, run on embedded devices, and easily integrate with other languages.
Analogy: C/C++ is a nightclub with no bouncers. Anyone can go in, mess with the DJ equipment, and start fights (memory leaks, crashes). It’s a very fast, wild party, but someone eventually gets hurt. Java/Python is a nightclub with a janitor (Garbage Collector) who constantly walks around cleaning up empty cups while you dance. It’s safe, but sometimes the janitor stops the music to clean, causing awkward pauses. Rust is a nightclub with a strict bouncer at the front door (The Borrow Checker). He checks your ID and your intentions before you even enter the building. If you look like you’re going to cause trouble, you aren’t allowed in. But once you are inside, there are no janitors stopping the music, and because everyone inside was vetted, the party is both incredibly fast and perfectly safe.
Like C: C is 50 Years Old. Should You Learn Rust?
Unlike Python and Java, which can have object classes:
Unlike Python and Java, which use a garbage collector (that increases Runtime program size) and pauses occassionally for automatic Garbage Collection:
Unlike Python and Java which use try/catch exceptions:
Unlike other languages: This Is How Rust Stops Memory Leaks
which can have several variables point to the same memory, which can cause parallel and concurrency issues, Rust has a clone method.
rustdoc command generates HTML documentation (like JavaDoc) without installing additional tools
Unlike Python & Go:
Unlike Java and C#:
Like shell scripts:
Data types larger than 128 bytes are copied with more expensive memcpy rather than inline code.
Like Python:
Unlike Python, JavaScript:
Unlike Zig:
Speed, Safety, Concurrency, Portability
Web Assembly, Embedded, Windows, macOS, Linux, BSD, iOS, Android,
Rust catches concurrency programming mistakes.
Because of the Ownership rules, Rust solves one of the hardest problems in programming: concurrent (multi-threaded) programming.
In languages like C++, data races (where two threads accidentally overwrite each other’s data) are a nightmare to debug. Rust make data races impossible because the Borrow Checker ensures that if a thread is accessing data, no other thread can mutate it unless you explicitly use safe locking mechanisms (like Mutex).
Unlike C, copies of data can be made, (which is slow for large data). Within Rust, to pass data to another part of your code, you don’t copy it , and you don’t share it freely (which is dangerous). Instead, you borrow using references (&).
Analogy for Rust strict borrowing rules:
If you write code that tries to use a variable after it has been deleted, or if two threads try to modify the same data at the same time, The Borrow Checker throws an error, and forces you to fix the logic before the program ever runs. This is why Rust developers say:
“If it compiles, it works.”
Stack overflow vulnerabilities not possible?
Videos comparing languages:
YouTube Playlists:
Rust developers are called “Rustlings” or “Rustaceans”.
Rust is the work of tens of thousands of contributors from around the world. https://thanks.rust-lang.org/rust/all-time/
Stack Overflow: Search for your specific error message. There’s a very high chance someone else has encountered it and found a solution .
Reddit (r/rust): A large and active community where you can ask questions and discuss challenges .
Rust Users Forum: The official Rust community forum, a great place for more in-depth technical discussion .
The Rust Foundation: The non-profit organization that stewards the Rust project also supports the ecosystem. They fund maintainers, support global community events, and work on critical infrastructure, which in turn helps improve the language and tools you use .
https://www.reddit.com/r/rust/
https://www.reddit.com/r/learnrust/
Rust projects (like PommeMC or Paru)
https://imposterdevs.com by Travis Media for weekly events
Rust is named after the rust family of parasitic fungi causing plant diseases with its brown spores.
Rust Belt Rust: conference held in the “Rust Belt” of the U.S.
RustFest: Europe’s @rustlang conference
VIDEO: RustConf2021 YouTube mix
RustCon Asia
Rust LATAM
Oxidize Global
VIDEO: Top 4 Rust career paths (and which one you should choose)</a>
I am not aware of a globally recognized certification for Rust developers. The core Rust team nor the Rust Foundation currently provide an official certification.
The Linux Foundation’s “Programming in Rust (LFD480)” is an instructor-led training combined with certification “money grab”.
Lists:
https://learning.oreilly.com/library/view/-/0642572230241/ The Rust Programming Language, 3rd Edition, March 2026 By Steve Klabnik, Carol Nichols and Chris Krycho
https://rust-book.cs.brown.edu/ is an interactive fork of doc.rust-lang.org/book = TRPL (“The official Rust Programming Language book”) by Steve Klabnik, Carol Nichols, and Chris Krycho. It references https://github.com/rust-lang/book
https://learning.oreilly.com/videos/-/9781491925447/continue VIDEO</a>: The Rust Programming Language: Fast, Safe, and Beautiful, 2015 By Jim Blandy
https://learning.oreilly.com/videos/oscon-2017/9781491976227/9781491976227-video306635/ 1h VIDEO: Rust for non-Rust developers - Hanneli Tavante (Codemine42) at OSCon 2017 Austin by Jim Blandy Borrowing
https://learning.oreilly.com/library/view/-/9781098176228/ Programming Rust, 3rd Edition, Oct 2026 By Jim Blandy, Jason Orendorff and Leonora F. S. Tindall
doc.rust-lang.org/rust-by-example = “Rust by Example references https://github.com/rust-lang/rust-by-example Learn by doing with annotated examples”
https://github.com/sunface/rust-by-practice Learning Rust By Practice, narrowing the gap between beginner and skilled-dev through challenging examples, exercises and projects.
rustlings.rust-lang.org “Rustlings: Small exercises to get you used to reading and writing Rust code”
https://github.com/PacktPublishing/Speed-up-your-Python-with-Rust
https://github.com/PyO3/maturin
https://github.com/Indosaram/rust-python-book
https://github.com/pretzelhammer/rust-blog Educational blog posts for Rust beginners
https://rustfoundation.org/rust-foundation-trusted-training/ $3,000
BekBrace and Hunt Sostanza
Arfan Zubi, with https://www.freecodecamp.org created 14 hr “Learn Rust Programming - Complete Course 🦀” 2023, referencing https://github.com/3rfaan/courses/tree/main/Rust/rust-by-practice/src at https://practice.rs/ translated to English https://practice-rust.beatai.org/
VIDEO: Packt: “Ultimate Rust Crash Course” Oct. 2020 with code at https://github.com/CleanCut/ultimate_rust_crash_course (don’t use Packt code repo) when Rust was at 1.89.0. Shows how to write an interactive Space Invaders game with audio, multithreading.
By @Jayson Lennon on
by Derek Banas
by @JeremyChone (from France)
by Michael Preston
On Udemy by others:
by Dmitri Nesteruk (“semi-retired” Quant in the UK) shows use of IntelliJ IDEA.
by Traversy Media
by anurag-garimella
by the Android team at Google
By David MacLeod (Canadian in South Korea):
Others:
https://github.com/rust-lang/rustlings Small exercises to get you used to reading and writing Rust code!
https://github.com/microsoft/RustTraining Beginner, advanced, expert level Rust training material
https://github.com/TheAlgorithms/Rust All algorithms written in Rust
https://github.com/AnasImloul/Leetcode-Solutions A repository with over 7000 solutions to more than 1800 Leetcode problems written in C++, Python, Java, Javascript & Golang. by Anas Imloul
https://github.com/mainmatter/100-exercises-to-learn-rust A self-paced course to learn Rust, one exercise at a time.
Advent of Code is (since 2015) an annual event offering daily programming challenges from December 1st to 12th, designed for various skill levels and languages, used for learning, practice, and competition. One puzzle unlocks each midnight at EST/UTC-5. https://www.reddit.com/r/adventofcode/
https://github.com/LinuxUser255/run_cmds
https://github.com/ShreyashSarage/file_handling_rust [No contributions in 2026] File Handling in rust by accepting the config file path in the command line arguments and passing the file path to the main.rs file to print the content of the given file
https://github.com/rustfs/rustfs 🚀2.3x faster than MinIO for 4KB object payloads. RustFS is an open-source, S3-compatible high-performance object storage system supportin…
https://github.com/rustcc/RustPrimer The Rust primer for beginners. Chinese. From 2016. We need native English speaker help us modify the translation.
https://github.com/rust-lang/rustfmt rustfmt // Format Rust code
https://github.com/rust-lang/rust-clippy A bunch of lints to catch common mistakes and improve your Rust code. Book: https://doc.rust-lang.org/clippy/
https://github.com/joaoviictorti/RustRedOps Repository for advanced Red Team techniques focused on Rust
https://discord.com/invite/mnQfzktNu9
So that we can confidently call each of the 393 wonderful modules from our own custom modules, I generated file algorithms.csv to enable automatic execution of each module to:
The algorithms.csv file contains these fields updated by run-algorithms.rs:
The 22 categories are listed in the lib.rs file to hold reuseable functions.
mod.rs files are not in the .csv file because they’re in every category folder.
These contain sub-categories (which my .csv generator mixed up):
Modules having a second catgory:
Oz/Warp, which generated the file, iteratively identified errors from this prompt:
These files exist but are not listed in DIRECTORY.md:
Explanations not in algorithms.csv:
https://github.com/TheAlgorithms/Algorithms-Explanation/tree/master/en https://github.com/TheAlgorithms/Rust https://github.com/TheAlgorithms/Rust/blob/master/DIRECTORY.md
Sample summary output:
Summary: 99 passed, 0 failed, 1 skipped (100 selected) Elapsed: 16.409s Log file: /Users/johndoe/github-wilsonmar/Rust-algorithms/target/run-algorithms-20260623T142830.169122000Z.log Log bytes: 121633 bytes Summary file: /Users/johndoe/github-wilsonmar/Rust-algorithms/target/run-algorithms-20260623T142830.169122000Z.txt
Prompt to create the program:
create program run-algorithms.rs in new utils folder in the src folder.
Create Rust code to load file algorithms-001.csv and loop through each row.
Read arg named startnum and num2run in program call command.
Execute with crate command beginning from startnum for count in num2run.
If startnum is not specified, use hard-coded default of 1.
If num2run is not specified, use hard-coded default of 1.
To algorithms-001.csv add column "status" to the right of column "seq" and change run-algorithms.rs to update the status to contain "PASS" or "FAIL" after running each row.
Stop execution if a module on a row returns FAIL.
Add run-algorithms.rs run of clippy before cargo test. Skip the test if clippy has an error.
Rather than output to stdout, write to a run log file in the workspace /target folder.
The run would be quicker because run progress is not shown in STDOUT interactively.
The log file name folder is specified in .gitignore so it doesn't get committed up.
Near the end of a run, report in STDOUT a run summary of run elasped time, number of .rs run, skipped.
Include a precise UTC timestamp as of start of run to each log's filename.
Add calculation of log file output byte size and location. Report that in the run summary.
Zip the run log file.
Do not include run summary in the run log file, to make file length calc straightforward.
Store run summary statistics by adding to a new summary-run-algorithms.csv file.
Check run:
cargo build --bin run-algorithms 2>&1
cargo run --bin run-algorithms -- --startnum 1 --num2run 1 2>&1
cargo fmt --manifest-path /Users/johndoe/github-wilsonmar/Rust-algorithms/Cargo.toml -- src/utils/run-algorithms.rs && cargo run --manifest-path /Users/johndoe/github-wilsonmar/Rust-algorithms/Cargo.toml --bin run-algorithms -- --startnum 1 --num2run 1
Full run: remove – –startnum 1 –num2run 1 to run all rows
cd /Users/johndoe/github-wilsonmar/Rust-algorithms
echo "=== build ==="
cargo build --quiet --bin run-algorithms 2>&1; echo "build_exit=$?"
echo "=== rows 1-3 BEFORE (seq,status,runsecs) ==="
awk -F, 'FNR>=2 && FNR<=4{print " "$1","$2","$3}' algorithms-001.csv
sed -i '' 's/^2,PASS,/2,SKIP,/' algorithms-001.csv
echo "=== run rows 1-3 with row 2 marked SKIP ==="
cargo run --quiet --bin run-algorithms -- --startnum 1 --num2run 3 > /tmp/skip-test.log 2>&1; echo "run_exit=$?"
grep -E "^\[|status :|^Summary:|^Elapsed:" /tmp/skip-test.log
echo "=== rows 1-3 AFTER (row 2 must remain SKIP, runsecs unchanged) ==="
awk -F, 'FNR>=2 && FNR<=4{print " "$1","$2","$3}' algorithms-001.csv
sed -i '' 's/^2,SKIP,/2,PASS,/' algorithms-001.csv
echo "=== rows 1-3 RESTORED ==="
awk -F, 'FNR>=2 && FNR<=4{print " "$1","$2","$3}' algorithms-001.csv
github.com/QMHTMY/RustBook: A book about Rust Data Structures and Algorithms.
Leetcode???
In my https://github.com/wilsonmar/rustlang/../bad-client.rs
https://rust-book.cs.brown.edu/ch21-02-multithreaded.html provides sample code for a badly-behaved client app to test defensive error detection and correction behavior by servers interacting with various protocols (HTTP, gRPC, OLTP, etc.).
Program invocation commands provide a way to select what anti-pattern and worst practice to inflict
There are many alternative technologies to hold data:
The sequence of concepts: https://github.com/0atman/noboilerplate
The extropy.io video course is designed to take you from a beginner to a confident Rustacean, specifically tailoring examples and projects towards blockchain and smart contract development. Learn the Rust programming language with a focus on blockchain development, tailored for developers looking transition from other languages to Rust. Example code runs within Codespaces. Nothing in https://github.com/ExtropyIO/RustCourseExamples
To see what version of the Rust compiler on your machine: see https://www.rust-lang.org/tools/install
rustc --version
At time of writing: rustc 1.91.0 (f8297e351 2025-10-28) Previously: rustc 1.25.0 (84203cac6 2018-03-25)
THe latest version is available in Homebrew on MacOS:
brew info rust
✔︎ JSON API packages.arm64_tahoe.jws.json Downloaded 15.2MB/ 15.2MB ==> rust ↑: 1.95.0 → stable 1.96.0 (bottled), HEAD Safe, concurrent, practical language https://www.rust-lang.org/ Old Names: rustfmt Installed (on request) From: https://github.com/Homebrew/homebrew-core/blob/HEAD/Formula/r/rust.rb License: Apache-2.0 OR MIT ==> Installed Kegs and Versions rust ↑ 1.95.0 → 1.96.0 (4,766 files, 372.3MB) [Linked] ==> Dependencies Required (6): libgit2 ↑, libssh2 ✔, llvm ↑, openssl@3 ✔, pkgconf ✔, sqlite ↑ Recursive Runtime (15): all installed ✔ ==> Options --HEAD Install HEAD version ==> Caveats Link this toolchain with `rustup` under the name `system` with: rustup toolchain link system "$(brew --prefix rust)" If you use rustup, avoid PATH conflicts by following instructions in: brew info rustup The following rust executables are shadowed by other commands earlier in your PATH: cargo (shadowed by /Users/johndoe/.cargo/bin/cargo) cargo-clippy (shadowed by /Users/johndoe/.cargo/bin/cargo-clippy) cargo-fmt (shadowed by /Users/johndoe/.cargo/bin/cargo-fmt) clippy-driver (shadowed by /Users/johndoe/.cargo/bin/clippy-driver) rust-gdb (shadowed by /Users/johndoe/.cargo/bin/rust-gdb) rust-gdbgui (shadowed by /Users/johndoe/.cargo/bin/rust-gdbgui) rust-lldb (shadowed by /Users/johndoe/.cargo/bin/rust-lldb) rustc (shadowed by /Users/johndoe/.cargo/bin/rustc) rustdoc (shadowed by /Users/johndoe/.cargo/bin/rustdoc) rustfmt (shadowed by /Users/johndoe/.cargo/bin/rustfmt) Running these by name will not invoke the version provided by Homebrew. Disable this behaviour by setting `HOMEBREW_NO_PATH_SHADOW_CHECK=1`. Hide these hints with `HOMEBREW_NO_ENV_HINTS=1` (see `man brew`). ==> Analytics install: 33,703 (30 days), 113,069 (90 days), 437,923 (365 days) install-on-request: 23,022 (30 days), 80,709 (90 days), 308,521 (365 days) build-error: 297 (30 days)
Previously:
rust: stable 1.55.0 (bottled), HEAD ==> Analytics 2018-03-25 install: 32,304 (30 days), 87,338 (90 days), 284,700 (365 days) install-on-request: 18,508 (30 days), 46,834 (90 days), 155,109 (365 days) build-error: 0 (30 days)
To install or upgrade using Homebrew on MacOS:
brew install rust
==> Downloading https://ghcr.io/v2/homebrew/core/libssh2/manifests/1.10.0 ==> Downloading https://ghcr.io/v2/homebrew/core/libssh2/blobs/sha256:70c0928f2c ==> Downloading from https://pkg-containers.githubusercontent.com/ghcr1/blobs/sh ==> Downloading https://ghcr.io/v2/homebrew/core/rust/manifests/1.55.0 ==> Downloading https://ghcr.io/v2/homebrew/core/rust/blobs/sha256:4486ea172caf9 ==> Downloading from https://pkg-containers.githubusercontent.com/ghcr1/blobs/sh ==> Installing dependencies for rust: libssh2 ==> Installing rust dependency: libssh2 ==> Pouring libssh2--1.10.0.mojave.bottle.tar.gz 🍺 /usr/local/Cellar/libssh2/1.10.0: 184 files, 970.1KB ==> Installing rust ==> Pouring rust--1.55.0.mojave.bottle.tar.gz ==> Caveats Bash completion has been installed to: /usr/local/etc/bash_completion.d ==> Summary 🍺 /usr/local/Cellar/rust/1.55.0: 30,682 files, 742.4MB ==> Caveats ==> rust Bash completion has been installed to: /usr/local/etc/bash_completion.d
grep -qF '/opt/homebrew/opt/rustup/bin' ~/.bash_profile 2>/dev/null || echo 'export PATH="/opt/homebrew/opt/rustup/bin:$PATH"' >> ~/.bash_profile
export PATH="/opt/homebrew/opt/rustup/bin:$PATH"
rustup default stable
rustup --version
rustc --version
cargo --version
rustup 1.29.0 (2026-03-05) info: This is the version for the rustup toolchain manager, not the rustc compiler. info: the currently active `rustc` version is `rustc 1.91.0 (f8297e351 2025-10-28)` rustc 1.91.0 (f8297e351 2025-10-28) cargo 1.91.0 (ea2d97820 2025-10-10)
Alternately, if you used rustup to install:
Doug Milford (lambdavalley.com) uses Visual Studio Code (VSCode) IDE on YouTube:
There is Rust Rover and Freemium Fleet from JetBrains. VIDEO VSCode extensions to get comparable features:
VisualRust IDE?
git clone https://github.com/wilsonmar/rustlang-samples --depth 1
cd rustlang-samples
rustfmt --print-config default >default-rustfmt.toml
PROTIP: In the rustfmt.toml file, only specifies overrides (non-default) setting values. Its faster for the program to ignore a comment.
brew install curl
curl -O https://raw.githubusercontent.com/ravyne/rustfmt-expander/refs/heads/main/rustfmt-expander.awk
code rustfmt-expander.awk
cp rustfmt-expander.awk ~/.local/bin/.
Folder ~/.local/bin is a common component in the $PATH within .bash_profile to make it known within CLI shells.
brew install gawk
gawk -f rustfmt-expander.awk -- default-rustfmt.toml >> documented-rustfmt.toml
rm default-rustfmt.toml
The above only needs to be done once.
cp documented-rustfmt.toml rustfmt.toml
rm documented-rustfmt.toml
code rustfmt.toml
This makes it easy to see which settings is using the default and which the override.
rustup component add rustfmt
rustfmt --version
At time of this writing, the response:
rustfmt 1.8.0-stable (f8297e351a 2025-10-28)
cargo fmt
FIXME: no response???
open https://marketplace.visualstudio.com/items?itemName=rust-lang.rust-analyzer
The Cargo.lock file:
PROTIP: For a binary crate (not a library), Rust’s convention recommends committing Cargo.lock so builds are fully reproducible. /Cargo.lock to only ignore a root-level one, then commit src/hello-rust/Cargo.lock.
View the .gitignore file in my by GitHub:
# will have compiled files and executables
/target/
target/
# Remove Cargo.lock from gitignore if creating an executable, leave it for libraries
# More information here https://doc.rust-lang.org/cargo/guide/cargo-toml-vs-cargo-lock.html
Cargo.lock
# Backup files generated by rustfmt:
**/*.rs.bk
.obsidian
.trash
# macOS
.DS_Store
REMEMBER: The target folder is where compiled assets (executables) are stored.
cargo add clippy --dev
cargo clippy -- -D warnings
REMEMBER: “.rs” is the file extension for Rust program source files.
export PATH="/opt/homebrew/opt/rustup/bin:$PATH"
cd src
cargo new hello-rust
cd hello-rust
cargo run
Creating binary (application) `hello-rust` package note: see more `Cargo.toml` keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html Compiling hello-rust v0.1.0 (/Users/johndoe/github-wilsonmar/rustlang-samples/src/hello-rust) Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.75s Running `target/debug/hello-rust` Hello, world!
Notice that in the folder created is a hello.rs file. In the src/hello-rust folder:
code hello-rust
PROTIP: At the top of the file:
#[allow(unused_variables)] // To squash warnings about unused vars
#[allow(unused_arguments)] // To squash warnings about unused arguments
REMEMBER: In the Rust development environment, all tools are installed to the directory
~/.cargo/bin
That’s where the Rust toolchain is installed, including rustc, cargo, and rustup.
Install https://crates.io is the Rust language’s library registry (like npm and pypi). On Linux and macOS systems:
curl https://sh.rustup.rs -sSf | sh
Response:
... warning: rustup should not be installed alongside Rust. Please uninstall your existing Rust first.
Notice the most downloaded libraries are rand, syn.
Build
cargo build
View file “Cargo.taml” (where toml stands for “Tom’s obvious minimal language”):
[package] hame="hello" version="0.0.1" authors=["John Doe <john.doe@gmail.com>] edition="2024"
REMEMBER: edition refers to the year of the Rust compiler to be used. 2018 is the lastest one as of this writing. (This should really be “Vintage”).
In the toml file: Toolchain management with rustup (at https://github.com/rust-lang/rustup.rs) which manages builds on all platforms that Rust supports, enabling installation of Rust from the beta and nightly release channels as well as support for additional cross-compilation targets.
[dependencies] rand = "^0" // for random pyo3 = "~0.19.0" chrono = "0.4" // for time stamps
six-week release cycles
Others not used:
nalgebra = "0.34.0"
ndarray = "0.17.2"
num-bigint = { version = "0.4", optional = true }
num-traits = { version = "0.2", optional = true }
[dev-dependencies] quickcheck = Property-based testing library that auto-generates random inputs to find bugs quickcheck_macros = Provides the #[quickcheck] attribute that turns functions into test cases automatically
REMEMBER: Modules in dev-dependencies (not dependencies) are only used in tests. Think of them like keeping your gardening tools in the shed (dev-dependencies) rather than the living room (dependencies) — you only need them when you’re actually working in the garden (writing tests), not when people visit your house (using your crate). Cleaner dependency tree: Your crate’s public API doesn’t expose these testing tools. When someone adds your crate to their project, they won’t waste time compiling testing libraries.
REMEMBER: You import them in #[cfg(test)] code blocks, not in your main library code.
// In src/lib.rs (your main code) - NO quickcheck imports here:
pub fn add(a: i32, b: i32) -> i32 {
a + b
}
// In tests/basic_tests.rs - quickcheck lives here:
#[cfg(test)]
use quickcheck::{TestResult, quickcheck};
#[test]
fn test_addition() {
quickcheck(|a: i32, b: i32| a + b == b + a); // Auto-generates 100+ random cases
}
The Rust standard library source is in the Rust repo at:
https://github.com/rust-lang/rust/blob/main/library/std/src/lib.rs
Docs about it are at: https://doc.rust-lang.org/std/
After installing rust-src, the local installed source path on Linux is at: lib/rustlib/src/rust/library
There are two ways of building a Rust program. One is cargo referencing a .taml file, and another is using the rustc command:
rustc hello.rs
On MacOS & Linux, compilation creates a “hello” file (with no file extension).
On Windows, compilarion creates a “hello.exe” file.
Move the executable to the target folder where it will execute.
rustc --explain E0308
REMEMBER: Press Q on the keyboard to exit.
./hello
The response is “Hello, World!”.
Alternately, run by
cargo run
So that I can compile and run with a single command:
cr hello
That is enabled by this line in $HOME/aliases.sh
alias cr="cargo run"
alias crv="cargo run --verbose"
after copying from my: https://github.com/wilsonmar/macos-setup/blob/main/aliases.sh
and adding into ~/.bash_profile a command to run the file:
source $HOME/aliases.sh
rustc --explain E0308
Here’s a sample function definition:
// use std::fs;
// use std::io;
fn read_server_list() -> Result<String, io::Error> {
match fs::read_to_string("Servers.txt") {
Ok(servers) => OK(servers),
Err(e) => Err(e)
}
}
fn main() {
let server = read_server_list_result()
.unwrap_or("localhost".to_string());
}
read_to_string is a built-in function that tries to open a file, read its entire contents, with a Result of a String type returned or an Error type. With Rust, there is no try, only do.
Result is an enum, a type that has two possible outcomes determined by match:
Alternately, Rust provides a built-in operator called the ? (question mark) operator “fs::” that replaces the whole match block with one line:
fn read_server_list() -> Result<String, io::Error> {
fs::read_to_string("Servers.txt")
}
The ? automatically unwraps Ok or returns Err. If read_to_string returns Ok, the ? extracts the String. If it returns Err, the ? immediately stops the function and returns the error to the caller.
"\x1b[1m" begin
"\x1b[0m" reset
println!(
print!(
eprintln!( ???
REMEMBER: Unlike JavaScript or Go: calling an Async function are lazy: doesn’t actually eagerly run the async function.
Example:
async fn fetch_user() {
println!("Fetching user");
}
fn main() {
// Future:
log_user(); // lazy
}
REMEMBER: Unlike JavaScript or Go: the Async function is not built into the Runtime
* JS: Promise -> Event loop -> Callbacks
* Go: Goroutine -> Scheduler -> OS thread
NOTE: “Embassy” and Tokio are 3rd-party async runtimes for Rust.
To make a futures run, hand off a task. Using the most popular async runtime manager:
async fn fetch_user() {
println!("Fetching user");
}
#[tokio::main] // macro to set up thread pool.
async fn main() { // the root task
// sequential execution of lines:
let user = fetch_user().await; // await sequentially. Return expected.
tokio::spawn(log_user()); // schedule wrapped task to run. No return expected. Fire and forget.
}
// Interleaving: 1.1 seconds total:
let (config, db) = tokio::join!(
load_config();
connect_to_db(),
):
// ... fetch_user()
Structured Concurrency & Cancellation safety:
tokio::select! { // race:
user = send_message(&mut stream, payload) => {
// message sent
}
// Implicit cancellation and cleanup after 5 second timeout by Runtime:
_ = sleep(Duration::from_secs(5)) => {
// treat connection as corrupted for idiomatic recovery:
let _ = stream.shutdown().await;
}
}
Sync <-> Async Interop:
async fn fetch_options_and_calc_greeks(symbol: &str) -> u64 {
// async OPRA request:
let quotes = fetch_option_quotes(symbol).await?:
// CPU-heavy Greeks calculation moves to blocking pool:
let result = tokio::task::spawn_blocking(move || calc_greeks(quotes).await?;
}
Rust Parallel/Async vs. EVM Synchronous: COURSE: Rust has become the industry standard for high-performance blockchain development. Use Rust instead of Solidity. Rust is the native language for Solana, Near, and Polkadot, and is unlocking new performance levels on EVM (Etherium Virtual Machine) chains like Arbitrum Stylus. It also underpins the logic of Starknet. Whether you are building next-gen DeFi or high-frequency trading dApps, a solid foundation in Rust is your gateway to these ecosystems.
80,000 requests per second from FastAPI Python vs. Rust vs. 2,000 = 40x speedup running concurrently.
onnx model format
“fn” defines
If not referencing a variable in the signature, prefix with an underline.
“impl”
Function names ending with an exclaimation mark (!), such as println!</t> are macros.
format! macro
select! macro
let mut v = vec![1,2,3];
use statements above main() are like Python import.
Standard library: https://doc.rust-lang.org/std/… use std::collections::HashMap; instead of Solidity Mappings.
Crates is the registry of cargo (packages) referenced by use.
Add the random number package in the toml file under [dependencies]
rand = “0.6.5”
https://github.com/muhammad-fiaz/logly a Rust-powered, Loguru-like logging library for Python that combines the familiarity of Python’s standard logging API with high-…
https://github.com/open-telemetry/opentelemetry-rust The Rust OpenTelemetry implementation
Log4r for Logging ???
Rust Threads are portable across platforms (macOS, Linux, etc.)
To spwan a thread to run concurrently in an allocated memory:
use std::thread;
fn mail(){
let handle = thread::spawn(move || {
// do stuff in a child thread
});
// Do stuff simultaneously in main thread.
// Wait until thread has exited:
handle.join().unwrap()'
}
PROTIP: Alternately, use awake.
Criterion crate has a separate directory and thus separate files from tests.
To benchmark non-public methods, use feature flags and wrappers.
github.com/tokio-rs/tokio for concurrent runtime.
Blocks.
Nested blocks.
Variables hoisted, shadowed within an inner block.
The assumption is that variables are immutable by a definition statement such as: x: i2 To make a veriable mutable: x: &mut i2
A string can be define two ways: &str or String:
fn mail() {
let example_str: &stsr = "Howdy"; // immutable
let example_string: String = String::from("Partner");
}
“characters (u8s)” gives the impression that individual characters themselves are 8-bit, when inside a string, they can be 8-bit, 16-bit, 24-bit, or 32-bit depending on the character. The “u8s” specifies bytes of memory encoding the string, not individual characters.
Using “unicode.segmentation” package to handle graphemes
Unicode (not UTF-8) scalars
REMEMBER: By default, variables are stored in the Stack.
// Signed: i8, i16, i32 (default), ... isize (the platform's pointer type size)
let stack_i8: i16 = -10; // integer (whole) number.
// Unsigned: u8, u16, ..., u128, usize
let stack_f32: f32 = 20.1; // floating point.
let stack_char: char = 'a';
let some_data bool = true; // or boolean false</a> (without quotes)
REMEMBER: So they can be fast, stack Variables are fixed in size (cannot grow).
TODO: Rust Native Types vs. Storage Slots vs. Serialisation
REMEMBER: Collections cannot be stack variables.
fn main () -> {
let mut s = String::from("Hello");
s.push_str(",world!");
// let s2 = s; // invalid
println!("{}", s);
}
Casting enlarges a variable with the same value.
A Trait is an Interface.
A dyn-compatible trait can be the base trait of a trait object. A trait is dyn compatible if it is not an async fn which has a hidden Future type.
Generics reduces code duplication by adding flexibility downstream: Instead of defining structs with diffent types: placeholder types,
struct Point<T> {
x: T,
y: T,
}
The Rust compiler substitutes T with i32.
fn main() {
let a = Point { x: 100, y: -1_f32 };
println!("x = {} y = {}, a.x, a.y );
let b = Point { x: 10.1, y: -2.3 };
println!("x = {} y = {}, b.x, b.y );
Ownership and Borrowing is at the heart of Rust. But this can be a daunting challenge to many new to Rustlang.
coding for stack and heap (smart pointers): which houses collections which needs to grow
### Ownership: Borrow Checker
This keeps developers from spending hours or days hunting down data race conditions.
Enums make nulls unnecessary.
Null safety: Option Enum
enum Option
Explicitly handle missing
A closure is an anonymous function. Aka Lambda.
A closure gives an inner function access to an outer function’s scope, even after the outer function has returned.
A closure is a function bundled together (enclosed) with references to its surrounding state (the lexical environment).
In JavaScript, closures are created every time a function is created, at function creation time.
To use a closure, define a function inside another function and expose it.
To expose a function, return it or pass it to another function.
Unlike Java, the Rust language does not have “class inheritance” features.
Traits were added in Rust 0.4 as a means to provide inheritance;
interfaces were unified with traits and removed as a separate feature.
Use Traits to define flexible behavior.
For interfacing with C, Rust has a foreign function interface (FFI) that can be called from, e.g., C language, and can call C. While calling C++ has historically been problematic (from any language), Rust has a library, CXX, to allow calling to or from C++, and “CXX has zero or negligible overhead.”
The type system supports a mechanism similar to type classes, called traits, inspired by the Haskell language. This facility is for ad hoc polymorphism, achieved by adding constraints to type variable declarations.
Rust Result and Option types …
“Once you’ve used them, any language with null starts to feel like a loaded gun pointed at your foot.”
VIDEO: Rust in the Browser for JavaScripters: New Frontiers, New Possibilities by Coding Tech
@mathewhaynesonline “AI for Web Devs”
https://www.youtube.com/watch?v=QXJ0wKBLt-8 Rust and GraphQL: A match made in heaven
By the distinguished Noah Gift (US expat in Valencia, Spain), Liam Parker, Alfredo Deza at Pragmatic AI Labs: https://github.com/paiml https://github.com/noahgift/continuous-integration for .github/workflows
If you have an OReilly subscription:
A. 1h Using Rust with Python Nov ‘23
B. 5h Rust for Pythonistas Nov ‘23 creates a Python with Make file, Polars tests.
C. 4h Rust LLMOps Nov ‘23 AWS Code Whisperer Live Coding Rust Cargo Lambda using Simple Browser:
D. AWS Builder Center: With a Coursera subscription (~$400/year), earn a career certificate you can add to your LinkedIn profile, resume, or CV. Share it on social media and in your performance review. AI Tooling Specialization: Build and deploy production AI systems using Rust on AWS. Master 20 courses with projects spanning foundation models, prompt engineering, security in 75 hours of videos:
https://www.coursera.org/specializations/building-cloud-computing-solutions-at-scale The Duke University Building Cloud Computing Solutions at Scale Specialization is a four-course foundation covering serverless, containers, data engineering, and MLOps on AWS:
Databricks
X. Rust Fundamentals Bootcamp in 6 hours over 5 weeks for $20/month.
VIDEO “you need to build a RUST desktop app!! by Travis Media” uses Slint UI framework
MYAPPNAME="myapp"
cargo generate --git https://github.com/slint-ui/slint-rust-template --name "$MYAPPNAME"
cd "$MYAPPNAME"
cargo build
BOOK: “The Rust Programming Language” at rust-lang.org/learn with code at https://github.com/rust-lang/rustlings/
https://doc.rust-lang.org/rust-by-example/index.html
[3] BOOK: Manning: “Rust in Action” Aug. 2021 [at OReilly.com] by Tim McNamara, with https://github.com/rust-in-action/code
At the Rust YouTube channel are recordings of meetings.
Bastian Gruber, author of VIDEO: manning.com/books/rust-web-development and https://rustwebdevelopment.com covers Logging, Error Handling, Vec, HashMap, String, Traits, https://git.sr.ht/~gruberb/onetutorial
“Rust, Wright’s Law, and the Future of Low-Latency Systems” at ScyllaDB’s P99 Conf. by Bryan Cantrill
https://www.youtube.com/watch?v=Uqi9xwlFbEc
https://medium.com/@mithi/genetic-algorithms-in-rust-for-autonomous-agents-an-introduction-ac182de32aee https://github.com/mithi/rusty-genes A Rust implementation of a genetic algorithm to solve the traveling salesman problem with animated visualizations
https://github.com/ExtropyIO/AwesomeZK https://academy.extropy.io/pages/courses/zkmaths-course.html https://maths.extropy.io https://github.com/ExtropyIO/ZeroKnowledgeBootcamp ZKP (Zero Knowledge Proofs) protocols.
Multiplicative inverses and field constraints in ZK
Lifecycle:
Frameworks & Tools:
Techniques:
https://github.com/nnethercote/perf-book/blob/master/src/heap-allocations.md cd /Users/johndoe/github-wilsonmar/rustlang-samples/src/hello-rust && sudo cargo flamegraph –release -o flamegraph.svg 2>&1
https://docs.google.com/presentation/d/1C1XEDoqdEEMkoTE7GqfsXgTkMh2z15CwkfFVXprVCaY/edit?usp=sharing Rust container cheat sheet
v030 diagram top @rustlang.md created 2021-10-03