Efficient, secure, performant concurrent systems programming that compiles to machine code on multiple platforms
This is about installing and using the infrastructure around the Rust programming language – the quickest way to use AI to building production-quality practical applications while learning the Rust language.
This page is NOT about the Rust game and Rustops.org
This references my github.com/bomonike/rustlang-samples repo and bomonike.github.io/rustlang website.
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.
Click on this link to pop-up a full-screen image of this diagram, or
click here for a gradual-reveal video

with narrative that logically explains how the various websites, folders, and files relate to each other within the sequence of work to create and run custom Rust programs. The narration below will soon be added to the video:
IDE: VSCode is commonly installed to edit files, assisted by extensions to display code with colored prompts.
When the bin folder path is made part of the $PATH variable by start-up scripts, executables in it become visible system-wide, cargo executable files become available on any folder in the CLI.
.gitconfig ???
Thus, cargo commands are typically issued from the module folder
The “.rs” file type suffix says that it’s processed by the Rust compiler, cargo build.
Additional custom .rs files can be added.
Each day, changes in the crates.io website are reflected in the lib.rs website which provides advanced filtering and categories. There are also additional libraries not in crates.io.
rustfmt.toml file.
Optimized executables can be added to the public crates.io registry of libraries. obtainable from shared registry are downloaded.
An “application” is built to meet the needs of a user persona - a standalone executable that uses multiple services.
Translation to different languages
CONTRIBUTING.md
CHANGELOG at the root. A CHANGELOG is not a dump of your Git commit history, but chronologically summarizee, in plain English, notable impacts. https://keepachangelog.com/en/1.1.0/ provides an example of the categories: Added, Changed, Deprecated, Removed, Fixed, Security.
VIDEO: Chapter 14.3: Manage complexity by using workspaces that consists of a main binary and several internal crates (libraries each with clear boundaries) that are always developed and released together. Create
cargo new my_app --bin # Creates a binary crate
cargo new my_lib --lib # Creates a library crate
cargo run -p my_app
See more Cargo.toml keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
## Playground
https://github.com/diegopacheco/rust-playground rust-playground is a set of rust useful code and poc.
## IDE Install
### VSCode & Rust Analyzer
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?
The Rust compiler, rustc, operates on one crate at a time. So compiling a large abstract syntax tree creates a large and lenthy sequential bottleneck. But multiple crates can be compiled in parallel on different CPU cores.
DEFINITION: A “monorepo” contains several separate crates in the same Git repo, within a single Cargo.lock file and Cargo workspace map defined in a Cargo.toml file and thus a single external dependency. Each crate binary executable has its own version number.
Link-Time Optimization???
The most common and effective structure for a production Rust workspace separates the codebase into three distinct categories:
workspace_root/ ├── Cargo.toml ├── Cargo.lock # the lockfile freezes your dependencies in time ├── apps/ # contains main.rs file as executable entry points ├── crates/ # target library creates (do not contain main.rs) │ ├── domain_billing/ │ ├── domain_inventory/ │ ├── domain_shipping/ │ ├── infra_postgres/ # contains concreate implementations to persist data │ └── infra_redis/ # contains ├── utils/ # helper crates that do not contain business logic. │ ├── secure_strings/ │ └── telemetry_helpers/ ├── public_api_gateway/ ├── public_api_server/ └── background_job_processor/
Under crates/, folder names have a prefix to specify what architectural layer each crate belongs in, to reduces cognitive friction while navigating the codebase:
Under each domain_ crate, modules (.rs files) are business entities, such as:
domain_inventory/src/
├── lib.rs
├── models/
│ ├── mod.rs
│ ├── product.rs
│ └── location.rs
├── events/
│ ├── mod.rs
│ └── stock_adjusted.rs
└── errors.rs
Under each infra_, modules (.rs files) define external integrations or technical implementation details:
infra_postgres/src/
├── lib.rs
├── connection.rs
├── queries/
│ ├── mod.rs
│ ├── insert_product.rs
│ └── fetch_location.rs
└── mappings.rs
main.rs files within the apps/ directory define executable entry points.
Such logic in main.rs should be thin to keep core logic isolated in library crates where it can be easily subjected to unit and integration testing.
Among helper crates in the utils/ directory, have small, focused crates rather than a single “lib.rs” dumping ground for miscellaneous shared functionality: timezone parsers, cryptographic hashers, string formatting macros, customized error types, etc.
my-workspace root/
├── Cargo.toml # Central Workspace root config
├── Cargo.lock # File created after first cargo build/run
├── my_app/
│ ├── Cargo.toml
│ └── src/
│ └── main.rs # binary
│ └── bin/
│ └── main.rs
├── my_lib/
│ ├── Cargo.toml
│ └── src/
│ └── lib.rs # library code
└── target/ # Shared build output directory
So they share a single Cargo.lock external versioning file. A [workspace] section in the Cargo.toml file defines member subdirectories belonging to the workspace.
The root workspace Cargo.toml defines what member custom code are built into a single crate for distribution.
[workspace]
members = [
"crates/*",
"utils/*",
"apps/*"
]
The root workspace Cargo.toml is where a centralized set of specific external crate version defined for use within all member crates:
[workspace.dependencies]
tokio = { version = "1.32", features = ["full"] }
serde = { version = "1.0", features = ["derive"] }
// Centralize internal path dependencies:
domain_billing = { path = "crates/domain_billing" }
All members need to follow the same lint rules:
[workspace.lints.rust]
unsafe_code = "forbid"
missing_debug_implementations = "warn"
[workspace.lints.clippy]
unwrap_used = "deny"
expect_used = "warn"
clone_on_ref_ptr = "deny"
Individual child crates reference versions in the workspace root Cargo.toml instead of specifying versions. Inside the child crate Cargo.toml files:
[package]
name = "secure_strings"
version.workspace = true
edition.workspace = true
authors.workspace = true
[dependencies]
tokio = { workspace = true }
serde = { workspace = true }
domain_billing = { workspace = true }
cargo new my_app --bin # Creates a binary crate
cargo new my_lib --lib # Creates a library crate
cargo run -p my_app
DEFINITION: A workspace is a container for several Rust projects which share the same target folder.
cargo run --bin [name]
“[name]” means that instead of specifying “server.rs” in the command, specify “server” because that’s the name for that file in Cargo.toml.
cargo run -p my_app
In the Workspace root config
# my-workspace/Cargo.toml
[workspace.dependencies]
serde = { version = "1.0", features = ["derive"] }
tokio = { version = "1.0", features = ["macros", "rt-multi-thread"] }
Use when your project is a workspace, a CLI tool with multiple sub-commands, or any project where you have multiple executable files and need to run a specific one.
???
“Vendoring” is the process of downloading and storing external libraries so that builds can occur locally, offline. This insulates builds from being affected by network or vendor infra outages and bad vendor version controls. Having previous versions of vendor libraries provides a way to conduct forensics.
A modern Rust web service can easily pull in two hundred transient dependencies. Vendoring these crates means committing tens of thousands of files and megabytes of third-party source code into your Git history. This can slow down repository cloning times and inflate the size of your storage mechanisms.
[source.crates-io]
replace-with = "vendored-sources"
[source.vendored-sources]
directory = "vendor"
Navigate to your repo’s Cargo.lockfile.
CAUTION: Every dependency specified in the lockfile will be downloaded, and take up disk space. Do you have enough disk space?
QUESTION: Transitive dependencies downloaded?
cargo vendor
Look at the frequency of recent commits. A repository with no activity for two years is a major risk, even if the code currently works perfectly.
Issues. If bug reports remain unaddressed, the project lacks the necessary maintainance bandwidth.
When you import a 0.x crate, future updates will likely require your manual refactoring of your code.
Many production teams utilize automated tools to monitor the registry and generate pull requests when new versions of dependencies are released. These pull requests trigger the automated test suite. If the tests pass, the team can review the changelog and merge the update confidently.
Does the library force you to allocate memory on the heap for every operation?
Does it spawn its own background threads (which will destroy your system invariants).
PROTIP: Pick a category (such as “Security”) and specialize at getting to know all the crates.
AI today (in 2026) is not only able to respond to questions based on its vast accumulated knowledge but now also can analyze error messages and automatically fix many issues, even across layers of architecture. Example response:
Build succeeds now. Fixed a type mismatch at main.rs:110 — check_url_virustotal expects &str but api_key was a String; passed it by reference.
This makes use of recent advances in “Chain-of-thought” which directs the LLM to reason sequentially through problems. Prompt chaining breaks complex analysis into discrete, verifiable pipeline stages.
To leverage creativity, developers are defining objectives and let the AI vary prompt text to iterative try then evaluate responses (adopting a TDD approach). Some call this “Iterative refinement”.
To work around being blocked when token credits ran out, Ollama (and its nomic-embed-text) is used with open-source models (from NVIDIA, Google, and China). OpenAI’s API supports the widest number of model providers. An example of messages about that:
The model is loaded and running (93% GPU), so it's not stuck loading — it's actively working but very slow (26GB model, mostly CPU-bound at only 7%/93% split suggests limited GPU offload). Since it's genuinely in-progress and not hung, let's just wait longer.
Many repos have a “NO AI SLOP” policy to protect themselves.
PROTIP: First of all, look at existing code and ask experienced team members to ensure consistency with established standards (whether formal or de facto).
So use AI to build in segments, identifying code to add such that you’re crafting the program:
rust function to humanize the display of the number of elapsed seconds.
Provide details such as:
For sub-second values, output using abbreviations such as ns, µs, ms, s.
The better AI provide test code without being asked.
The best AI recognizes typos and comes up with ideas without being asked:
Rather than growing the hardcoded list further (which is already a maintenance trap), I'll write a dedicated extractor for comparison queries that matches directly against the loaded country names in SQLite — a real fix, not a patch on a fragile pattern.
I am often surprised at compatibility note such as:
auth-git2 version mismatches with newer git2/rustc releases are a common cause of this error.
Analyze the AI response for programming techniques rather than blindly copying and pasting. PROTIP: Look at the version of Cargo.toml provided by AI. Edit the year to the latest (2024) so that you’re using the latest version associated with that.
Use follow-up prompt such as:
Explain the use of <`a> in rust code.
PROTIP: AI can save you a lot of time at finding crates which may have issues resolved in its code as well as documentation that you don’t have to write and review:
rust crate that humanize the display of the number of elapsed seconds.
The response can be pleasant surprises, such as
PROTIP: Prefer using crates (such as time-humanize and human-repr) which have “zero dependencies” that potentially allow security vulnerabilities to creep in.
PROTIP: TEAMWORK: Have your Security team review your use of external crates.
PROTIP: Once working (passes all the edits you can think off), commit the version and ecpore alternatives.
“Robust enterprise-worthy production code”, “easy to extend”, “performant”, and other nice objectives are achieved not by empty promises but the extent that these features are implemented. Here are specific coding features:
Plausible self-hostable instead of Google tracking: No cookies. Minimal impact on site speed. There are several frameworks for developing interactive apps in Rus, for the Autonomous Age of AI is for “Human In the Loop” to approve rather than initiate actions.
Use microsecond-level timings accuracy.
Forward and parse logs using Promtail or Fluentd crate libraries.
Issue alert to a SOC SIEM about security-relevant events and conditions defined in the MITRE ATT&CK framework or standard compliance controls (like PCI-DSS, HIPAA, or NIST). A SIEM (Security Information and Event Management) system is designed to cut through the noise of millions of mundane log entries to find the signals that indicate a threat, a breach, or a compliance violation. Such as failed access attempt, a malicious URL, email found.
Token usage tracking
Limit log restore handling accounts to Read-only access to prevent deletion ability.
Use the EmailRep.io and AlienVault API to determine Email Reputation - whether email addresses were reported as being used to distribute malware, phishing, or spam. There’s also IPQualityScore for a Threat Intelligence - where the domain is newly registered (a sign of malicious intent).
Phone numbers not reported to be spam-related
actix-web-prometheus crate to easily add a metrics middleware.
Timeout handling
Interaction to change storage backends by changing “aws” to “gcp”, “azure”, or “fs” (filesystem) as needed (AWS S3, Google Cloud Storage, Azure Blob Storage, local filesystem, etc.) object_store = { version = “0.10”, features = [“aws”]
The x402-reqwest client library supports custom payment selectors for complex multi-chain scenarios. It automatically intercepts 402 responses. It signs the payment requirement with a wallet, includes the signature in a Payment-Signature header, and retries the request.
the x402-axum Tower middleware layer intercepts HTTP requests to check if they include a valid payment header.
The Server (Payment Receiver) protects its API routes using middleware (like x402-axum). When a client requests a protected resource, the server responds with a 402 status and a Payment-Required header detailing the cost. Once payment is verified, access to the resource is granted. If no valid payment is detected, the API returns a 402 status code accompanied by a cryptographically signed payment request payload.
x402-rs workspace provide client and server-side libraries, with the latter offering a more modular, multi-chain support.
The x402-facilitator service handles the blockchain settlement with Base or Solana, running in Docker for easy setup.
The rust-x402 crate also provides a standalone facilitator binary. The rust-x402 crate supports frameworks like Actix Web and Warp.
We look for secrets leaking at EACH step in the development process:
Within the IDE, anomalies are instantly highlighted by extensions installed:
Type - Count - Severity - Description
For a fast, simple pre-commit hook to prevent committing secret keys into source code.
ripsecrets is known for being extremely fast (reportedly 95 times faster than other tools). It detects secrets by looking for variable assignments with names like “token”, “secret”, or “password” that contain random-looking strings.
security-harness-kit: A Rust CLI that scans for secrets, PII, and sensitive data. It can scan project paths and Git-staged files across many file types, including source code, Markdown, and even Office documents.
On MCP agents:
leakferret: An MCP-native secret scanner written in Rust. A key feature is that it can call the provider to verify which detected secrets are actually live and can rewrite the leak in your code to read from an environment variable instead.
On git push, more comprehensive scans:
SecretScout: A “blazingly fast, memory-safe CLI tool” for detecting secrets in git repositories. It’s a complete Rust rewrite of the popular gitleaks project, offering 10x faster performance with 60% less memory usage.
Kingfisher: An open-source secret scanner built in Rust by MongoDB. It features live secret validation and ships with over 950 built-in rules to detect and triage leaked credentials.
For scanning in CI/CD pipelines, use a pre-built GitHub Action guibranco/github-infisical-secrets-check-action
Use batch scanner on whole repos which may contain secrets already committed
argus: A high-performance batch security scanner that uses Shannon entropy analysis and multi-pattern matching to identify both known and unknown credentials.
infisical to “continuously” scan repositories, builds, and runtime artifacts for leaked secrets and misconfigurations.
Unless otherwise noted, crates mentioned above have signs of quality:
increasing downloads over time (are gaining in popularity)
updates within the last 6 months (has not been abandoned)
multiple maintainers
Please connect with me to join our code explaination and refactoring sessions.
– https://linkedin.com/in/wilsonmar
RANT: I think it’s a terrible idea to spend time writing another editor or operating system using Rust. Here I showcase creation of enterprise-worthy apps rather than basic/toy examples on the internet.
We are working on integrating here other code examples from GitHub.com:
Examples in Python:
https://github.com/arunprabusamy/course-explainer-app/tree/starter-template
https://www.youtube.com/watch?v=EUmK2tFAQfE = The Simplest AI Coding CLI in Pure Rust 50 Lines
grafana/augurs = Time series analysis for Rust, with bindings to Python and Javascript
https://github.com/RustScan/RustScan = Rust Scan - finds all open ports faster than Nmap.
https://github.com/dani-garcia/vaultwarden/ = Vaultwarden - unofficial Bitwarden compatible server written in Rust.
https://github.com/starship/starship = Starship - the cross-shell prompt written in Rust.
https://github.com/rustybuilder/rust-faces = Face Detection in Rust with Python Bindings
sudo rm -rf /Library/Developer/CommandLineTools
sudo xcode-select --install
brew trust --formula vectordotdev/brew/vector
brew tap vectordotdev/brew && brew install vector
Incredibly fast, low memory footprint, and handles both collection, parsing (transform), and routing logs. Recommended over Fluent Bit written in C and Filebeat written in Go. Vector does not block your application’s main thread. Instead of your app waiting for a network round-trip to the central server, your app writes logs to a local buffer (e.g., stdout, a local file, or a Unix socket). Vector reads from these local sources asynchronously. The app continues processing requests while Vector handles the network I/O in the background.
The Terminal program that comes with Operating Systems such as macOS are rather primitive compared to AI-enabled CLI Terminals. For one, legacy Terminal (including VS Code Terminal) cannot display images such as QR codes.
iTerm2 - Full color (macOS)
Sixel (short for “Six-bit elements”) is a graphics protocol that allows terminals to display bitmap images directly within the terminal window. It was originally developed by DEC (Digital Equipment Corporation) in the 1980s for their VT-series terminals.
echo -e "\ePq#0;2;0;0;0#1;2;100;100;0#2;2;0;100;0#1~#2~#3~\e\\"
viuer automatically falls back to ASCII art rendering. This ensures your PNG still displays something readable:
What folder should rust programs output files to from within the main.rs?
POLICY: ❌ Don’t hardcode filepath to just ./output.txt which this dumps files wherever the user runs the program – messy and unpredictable.
POLICY: The output folder (designated by a /) should be in .gitignore so that they are never pushed up to GitHub.
POLICY: ❌ Don’t write to the target/ folder — it’s for build artifacts, not your program’s output.
Use my __ function which puts outputs based on the OUTPUT_DIRPATH variable in .env file. If that is not specified, runs in Test environment output to hard-coded:
POLICY: ❌ Do not output to target/release and /debug folders the only cargo should output to:
If that is not specified in production, the standard practice is to
Use the ProjectDirs::data_dir() method to return a platform-specific path intended for your application’s persistent data files. https://docs.rs/envpath/0.0.1/x86_64-apple-darwin/envpath/struct.ProjectDirs.html ??? write to the user’s OS-specific data directory by using the directories crate to get the right path:
let output_filename = "a-very-fine-file.pdf"
let test_dir = std::path::Path::new(output_filename);
std::fs::create_dir_all(test_dir).unwrap();
PROTIP: Add to startup .bash_profile/.zshrc to update Rust utilities so have the latest version of the installer when you open a Terminal. This takes a few seconds.
REMEMBER: If you used Homebrew to install rustup, instead of rustup command to upgrade itself, use:
brew upgrade rustup-init
That’s instead of
The response:
Warning: Formula rustup-init was renamed to rustup. Warning: rustup 1.29.0_2 already installed
rustup --version
rustc --version
On Windows:
rustc.exe --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.96.0 (ac68faa20 2026-05-25)`
Alternately, for just the rustc version:
rustc --version
FUN FACT: Rust is released every 6 weeks
whereis rustc
rustc: /opt/homebrew/opt/rustup/bin/rustc /opt/homebrew/share/man/man1/rustc.1
whereis cargo
cargo: /opt/homebrew/opt/rustup/bin/cargo /opt/homebrew/share/man/man1/cargo.1
Read rustup.rs
DEFINITION: “toml” (Tom’s Obvious Minimal Language) contains “[]” section headers.
Inside the file, version=”0.1.0” is updated manually based on semver.org (Semantic Versioning) conventions.
edition=”2024” is described at
cargo info backup
The response at time of this writing:
Updating crates.io index
Downloaded backup v0.1.0
Downloaded 1 crate (85.6KiB) in 0.39s
backup #backup #cli #restore
create encrypted backups
version: 0.1.0
license: BSD-3-Clause
rust-version: unknown
documentation: https://github.com/nbari/backup
homepage: https://github.com/nbari/backup
repository: https://github.com/nbari/backup
crates.io: https://crates.io/crates/backup/0.1.0
For code completions, documentation on hover, etc.
VS Code is the most widely used editor for Rust.
VSCode users: install rust-analyzer (not “rust-lang.rust”). https://code.visualstudio.com/docs/languages/rust
IDEs are visual frontends for underlying debuggers like LLDB (on macOS/Linux) or GDB (on Linux) or the MSVC debugger (on Windows).
To enable breakpoints in VSCode, install the CodeLLDB extension by Vadim Chugunov by clicking this, then “Install”, “Continue”, “Allow”, “Trust publisher”:
https://marketplace.visualstudio.com/items?itemName=vadimcn.vscode-lldb
https://github.com/vadimcn/vscode-lldb
To set a breakpoint, click in the gutter (the empty space to the left of the line numbers) to place a red dot (your stop point). Then you press F5 (or go to Run -> Start Debugging). It will compile your code and stop execution exactly at that line, allowing you to inspect variables, view the call stack, and step through code line-by-line.
Dynamic Linking (Default):
By default, Rust dynamically links to your system’s C library (usually glibc on Linux). If you compile a binary on Ubuntu 22.04, it might refuse to run on an older server running CentOS 7 because the older server is missing the newer glibc version. (Low binary portability).
Static Linking (musl): You can tell Rust to compile against musl libc (e.g., cargo build –target x86_64-unknown-linux-musl). This bakes the C library directly into your executable. The resulting binary is a single file that will run on almost any Linux distribution from the last 15 years. (High binary portability)
Windows Binaries: By default, Rust statically links the Microsoft Visual C++ runtime into Windows executables. This means a Rust .exe is highly portable across different Windows versions and usually doesn’t require the user to install “VCRedist” packages.
git clone https://github.com/bomonike/rustlang-samples --depth 1
cd rustlang-samples
The repo currently has code for these sample Rust (.rs) program source packages:
useful-rust at https://github.com/bomonike/rustlang-samples/blob/main/src/useful-rust/src/main.rs
nato-phonetic-audio is an example of what to submit to crates.io
openai-chat between a front-end client talking with a chat bot.
started around Nov 2022
??? https://rust-analyser.github.io
I created it partly with assistance from Claude’s AI help.
Its Rust code is within a lib.rs file because the package is structured for upload to crates.io as a library for use by others.
cargo run --example speak_sentence -- "KLQ9" -v
The example file .rs name is auto-discovered.
Observe that the letters have a note to ensure proper pronounciation.
cd src/useful-rust
pwd
ls -al
At that folder, read the README.md for running useful-rust.
REMEMBER: Unlike Python and other languages, your working folder with Rust is a folder up from the main.rs file which is what all Rust code files are named.
PostgreSQL (pronounced “post-gres”) is the most popular SQL database, especially on local.
brew install postgresql
Install creates user “postgres” with permission to create and delete all databases..
brew install --cask dbeaver-community
psql -U postgres
Successful response means seeing:
psql (15.0) Type "help" for help. postgres=# _
postgres=# CREATE USER axum;
CREATE ROLE
postgres=# ALTER USER axum PASSWORD '1234';
ALTER ROLE
ALTER DATABASE axum OWNER TO axum;
$ psql -U axum axum psql (15.0) Type "help" for help. axum=#
Use SeaORM
Read: https://www.postgresql.org/download/
In my repo is an aliases.sh
source ~/aliases.sh
See my https://github.com/wilsonmar/mac-setup/main/blob/aliases.sh
This tutorial explains use of these aliases:
PROTIP: Many enterprise teams host starter files like in this repo to provide the team a consistent starting point, which reduces endless discussions when new people join the team.
Edit the Cargo.toml file for its sample settings.
CARGO_MANIFEST_DIR="$HOME/.config"
https://doc.rust-lang.org/cargo/reference/environment-variables.html
PROTIP: Coordinate the creation and maintenance of an install utility that enforces a consistent work environment among developers. This gets new team members productive much quicker, especially for pair programming. This also makes for easier testing, troubleshooting, and upgrades.
Several steps of processing is needed
Invocation steps for developer intervention when an error is identified along any of the steps.
CAUTION: It takes a few seconds to type and run commands, which distracts the concentration of many developers.
PROTIP: When developers manually control when utilities are run, they can invoke the operation before stepping away for a few minutes (to take a break, get a drink, go to the bathroom, etc.).
rgp
Use of this alias avoids typos from typing longer number of characters.
See https://git-scm.com/book/en/v2/Customizing-Git-Git-Hooks See https://github.com/Nutlope/aicommits for using AI to draft commit message text.
The script is careful to keep the scope of process to specific named files rather than any files which has changed.
“$CHANGED_ITEM”
Named files which have not actually been changed are not processed.
Different processes can occur on different types of files, using different utilities. Changes to .rs Rust code are processed using cargo utility commands.
PROTIP: When an undo is possible, we can confidently take automatic actions.
Capturing the state of code before processing it.
git add "$CHANGED_ITEM"
using the latest version of utilities
## Cargo fmt & rustfmt.toml
The cargo fmt command reformats code controlled by about 80 rules that have defaults which can be overridden by settings in a rustfmt.toml file.
REMEMBER: cargo fmt can be run (perhaps along with other utilities):
WHY? Reformatting is largely to keep code more readable.
PROTIP: The cargo fmt command is run for the sake of team consistency. Automatic code formatting reduces the need for debates (and stress) that erupt when a rogue team member arranges code in a way that violates standards. Automatic code formatting fixes rogue changes even before others find out about them.
CAUTION: There is a chance that cargo fmt causes compilation or run-time errors. There is also a chance that the team (as a whole) does not like the impact of a particular reformatting rule.
### git-commit script
The git client works by looking for a file named “git-commit” (without a suffix like .sh, within the repo’s .git/hooks folder) to see if there are instructions before executing the git action. See my https://wilsonmar.github.io/git-hooks
PROTIP: Check whether there is a new version of the utility on every use. Things can change quickly in today’s world. And it only take a second.
cargo fmt is NOT built into Cargo, but is an optional component that requires additional installation as an external command distributed with the Rust toolchain.
Within a CLI script:
rustup component add rustfmt
Within GitHub Actions yml:
# Install Rust toolchain with rustfmt:
- uses: dtolnay/rust-toolchain@stable
with:
components: rustfmt
https://github.com/dtolnay/rust-toolchain
Force everyone to format code according to the same rules by always running the cargo fmt command before every push to the team github.
WHY? Running as a GitHub Actions runner controlled by declarative yml upon every git push
The lowest cost is you have a MacMini,
# Check formatting (fail if anything is not formatted):
fmt:
name: Rustfmt
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Install the Rust toolchain
uses: actions-rust-lang/setup-rust-toolchain@v1
with:
components: rustfmt
- name: Enforce formatting
run: cargo fmt -all
run: cargo fmt all -- --check
.github/workflows/fmt.yml:
runs-on: ubuntu-latest to run the action on a self-hosted
TODO: specify use of a rustfmt.toml file in the GitHub Action request.
Each developer would run cargo fmt on his/her own.
CAUTION: PROTIP: immediately before the above cargo fmt command, save a copy of the target (using git) so that you can fall back if needed.
The utility has a set of default settings it uses.
Configuration options for each version https://rust-lang.github.io/rustfmt/ https://github.com/rust-lang/rustfmt Each configuration option is either stable or unstable. Stable options can always be used, while unstable options are only available on a nightly toolchain and must be opted into. To enable unstable options, set unstable_features = true in rustfmt.toml or pass –unstable-features to rustfmt.
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.
Raname file default-rustfmt.toml to “rustfmt.toml”
The “rustfmt.toml” in my rustlang-samples repo was generated using the rustfmt-expand.awk script at https://github.com/ravyne/rustfmt-expander
remove “#” in front of lines to activate changes from the default.
TODO: Changes to fmt rules would need to be applied to all code in the repository?
cargo update
cargo clean
cargo build
cargo build --timings
The “Unit Graph” visualizes the duration of each compiler invocation and the dependency chain, to identify bottlenecks.
The “Concurrency Graph” shows how many units are waiting, active, or inactive over time, for insight into parallelization efficiency.
pwd
Example:
/Users/johndoe/bomonike/rustlang-samples/src/useful-rust
cargo run --release
The Rust compiler aggressively optimizes the code – rearrange lines, inline functions, and remove unused variables, making it impossible for the debugger to map your stop points to the actual executing machine code.
cargo build
Success means a message such as:
Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.24s
RUST_LOG=debug cargo run -- -v -s
Parameters for each program should be defined in the program’s README
RUST_LOG=debug makes use of coding in the program to do logging. It can be removed.
Alternately, with JSON logs:
RUST_LOG=info cargo run 2>&1 | jq
2>&1 routes STDERR to screen.
### cargo on file change
Many find this annoying. But see for yourself.
cargo install cargo-watch
cargo watch -x check -x test -x run
cargo install cargo-udeps
cargo +nightly udeps 2>&1 | tail -60
This command requires the rustc nightly build or get an error. Example output:
`csv-rag-system v0.1.0 (/Users/johndoe/bomonike/rustlang-samples/src/csv2rag)`
└─── dependencies
├─── "openai-api"
├─── "qdrant-client"
├─── "reqwest"
├─── "text-splitter"
└─── "tokio"
This has limited usefulness to me, but an SBOM is useful.
TODO: This alternative is not working: cargo install tomlq RUSTPKG=”$(tq -r ‘.package.name’ Cargo.toml)”
Save a full indented dependency tree of crates and their versions for potential forensics later.
TECHNIQUE: Extract from Cargo.toml its name (RUSTPKG). Count rows in the SBOM and include that in the TREEFILE and at the bottom of the SBOM.
RUSTPKG="$(cargo pkgid | cut -d'#' -f2 | cut -d':' -f2)"
RTREE_ROWS="$(cargo tree | wc -l | xargs)"
TREEFILE="$RUSTPKG-$(date -u +%y%m%dT%H%M%SZ)-SBOM-$RTREE_ROWS.txt"
cargo tree >"$TREEFILE"
echo "$RTREE_ROWS" >>"$TREEFILE"
code "$TREEFILE"
Example TREEFILE: “csv-rag-system@0.1.0-260728T145928Z-SBOM-877.txt”
TECHNIQUE: xargs removes blank spaces from system variables.
TODO: Procedure to archive run history for forensics.
TODO: Incorporate the commands in the alias “rtree” defined within my alias in $HOME/aliases.sh.
csv-rag-system v0.1.0 (/Users/johndoe/bomonike/rustlang-samples/src/csv2rag)
├── anyhow v1.0.103
├── csv v1.4.0
│ ├── csv-core v0.1.13
│ │ └── memchr v2.8.3
├── openai-api v0.1.4
│ ├── derive_builder v0.9.0 (proc-macro)
│ │ ├── darling v0.10.2
│ │ │ ├── darling_core v0.10.2
│ │ │ │ ├── fnv v1.0.7
│ │ │ │ ├── ident_case v1.0.1
...
867
PROTIP: This is the “supply-chain” SBOM (Software Bill of Material) attestation (like a “food label”) that some customers ask to be delivered and retained with each release of software. It’s requested by US White House Executive Order 14028 signed by President Biden on May 12, 2021 but rescinded during the second Trump administration.
cargo install cargo-outdated
cargo outdated --aggressive | wc -l
–aggressive requests reporting of libraries with transitive dependencies
Specify –root-deps-only instead of –aggressive for just the named crates.
The count includes two lines for the heading:
530
cargo outdated --aggressive
Add –offline if you’re offline (as in no wifi).
Expect to see a table listing your dependencies, their current version, the latest compatible version, and the absolute latest version:
warning: Feature rustls-tls of package reqwest has been obsolete in version 0.13.4 Name Project Compat Latest Kind Platform ---- ------- ------ ------ ---- -------- ahash->cfg-if 1.0.4 --- Removed Normal --- ahash->getrandom 0.3.4 --- Removed Normal --- ahash->once_cell 1.21.4 --- Removed Normal cfg(not(all(target_arch = "arm", target_os = "none"))) ahash->version_check 0.9.5 --- Removed Build --- ahash->zerocopy 0.8.54 0.8.55 0.8.55 Normal ---
cargo audit
At time of running, it displayed “Vulnerable crates found!” within openai-client calling async-openai transitively calling backoff calling instant:
Version: 0.4.0
Warning: unmaintained
Title: `backoff` is unmaintained.
Date: 2025-03-04
ID: RUSTSEC-2025-0012
URL: https://rustsec.org/advisories/RUSTSEC-2025-0012
Dependency tree:
backoff 0.4.0
└── async-openai 0.24.1
└── openai-client 0.1.0
Crate: instant
Version: 0.1.13
Warning: unmaintained
Title: `instant` is unmaintained
Date: 2024-09-01
ID: RUSTSEC-2024-0384
URL: https://rustsec.org/advisories/RUSTSEC-2024-0384
Dependency tree:
instant 0.1.13
└── backoff 0.4.0
└── async-openai 0.24.1
└── openai-client 0.1.0
REMEMBER: As they say, “with Rust, you get the hangover before”. Use Clippy whinning as learning opportunities to write safer code.
├ Advisory: https://rustsec.org/advisories/RUSTSEC-2025-0012 ├ The [backoff](https://crates.io/crates/backoff) crate is no longer actively maintained. For exponential backoffs/retrying, you can use the [backon](https://crates.io/crates/backon) crate. ├ Announcement: https://github.com/ihrwein/backoff/issues/66 ├ Solution: No safe upgrade is available!
cargo deny
Migrate backoff to backon https://github.com/divviup/janus/pull/3769 shows a resolution on Apr 14, 2025
I asked AI “how to fix this” and got back:
The most sustainable solution is to update async-openai to a version that no longer depends on backoff. The latest version (0.41.1) still lists backoff as a dependency, but the maintainers may address this in a future release.
cargo update async-openai --verbose
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/
cargo clippy --manifest-path Cargo.toml 2>&1 | grep -E "warning:|error:|Finished" | sort -u
TODO: Define the commands above as my alias in $HOME/aliases.sh so you can invoke the command easily and frequently.
PROTIP: In the command above, “grep” creates a summary of one line per message. The “sort -u” presents only unique lines:
warning: called map(<f>).unwrap_or_else(<g>) on an Option value
warning: called map(<f>).unwrap_or(false) on an Option value
warning: non-binding let on an expression with #[must_use] type
warning: variables can be used directly in the format! string
</pre>
Learn!
If you’d rather be a pro than a mindless poser, do the work now to reap rewards in the years to come.
timestamp=$(date "+%Y%m%d_%H%M%S");clear;cargo clippy --manifest-path Cargo.toml --all -- -D warnings 2>"clippy-$timestamp.txt"
code "clippy-run-$timestamp.txt"
PROTIP: A clear command would enable you to quickly reach the top of a long output by pressing command+up arrow.
PROTIP: 2>”clippy_$timestamp.txt” sends the output to a file named with a ISO8601 UTC date/time stamp.
REMEMBER: Bookmark the link to Rust error codes
Each error has both bad example and good example code.
REMEMBER: To view on a browser from a Terminal app, hold down command to click on Clippy Lints for each of 809+ messages, such as:
https://rust-lang.github.io/rust-clippy/rust-1.96.0/index.html#collapsible_if
rustc --explain E0502
Press q to exit to the CLI prompt.
explain errors
Then:
explain fixes
An AI with an understanding of prior context would understand.
PROTIP: Take notes such as my:
https://bomonike.github.io/rustlang
cannot borrow * as mutable because it is also borrowed as immutable. CAUSE: an active immutable borrow when you try to create a mutable borrow. - Restructure your code. Ensure the immutable borrow is no longer used before the mutable borrow occurs. Sometimes, you can end the borrow earlier by limiting its scope with a block {} or by cloning the data if performance allows.
does not live long enough. CAUSE: A value is dropped (goes out of scope) while it’s still being borrowed. - Fix the lifetime. You may need to extend the lifetime of the value, take ownership (return an owned String instead of a &str), or add explicit lifetime annotations to your functions.
mismatched types. CAUSE: A variable or return value is of the wrong type. - Convert the type. Use .into(), as, or another method to convert the value to the expected type.
The Cargo.toml and clippy.toml files can contain specifications about what check to igore. Location is the ~/.cargo folder would apply to all Rust runs in any folder. Annoying examples:
warning: doc paragraphs should end with a terminal punctuation mark
https://doc.rust-lang.org/stable/cargo/ = The Cargo Book
https://github.com/joaoviictorti/RustRedOps TODO: Repository for advanced Red Team techniques focused on Rust
sed -n 's/.*\(STEP .*\)/\1/p' main.rs
TECHNIQUE: STEP numbers are zero-filled to ensure consistent vertical positioning.
STEP sequences : azure-rust @main.rs" STEP 01 - SILENT: TODO: Initialize logging."); STEP 02 - SILENT: Snapshot start time, memory, and disk as the baseline for deltas."); STEP 03 - SILENT: Collect variables in .env file:"); STEP 04 - SILENT: Run objectstore."); STEP 05 - SILENT: parse CLI program invocation flags:"); STEP 06 - SILENT: Display ENV_TYPE from env file (loaded above)."); STEP 07 - Print local and UTC timestamps."); STEP 09 - For production environments, logs need to be machine-readable."); STEP 10 - Print [package] variables in Cargo.toml."); STEP 11 - Display environment variables:"); STEP 12 - Display OS Environment Variables:"); STEP 13 - SECRET: OS name, user name (multi-os)."); STEP 14 - SECRET: The first MAC address may be spoofed within .bash_profile"); STEP 15 - SECRET: Networking SSID."); STEP 16 - SECRET: location info only when --secret / -s is passed."); STEP 17 - Set AzureRegionRegistry::new()"); STEP 18 - Map nearest Azure region to Latitude/Longitude:"); STEP 19 - Load configuration:"); STEP 20 - Azure: Create credentials:"); STEP 21 - Azure: Resource group (control plane)", STEP 22 - Azure: Provider registration (control plane)", STEP 23 - Azure: Storage account (control plane)", STEP 24 - Azure: Storage RBAC", STEP 25 - Azure: Key Vault (control plane)", STEP 26 - Azure: Key Vault RBAC", STEP 27 - Azure: Key Vault", STEP 28 - Azure: Service Bus namespace (control plane)", STEP 29 - Azure: Cosmos DB account (control plane):"); STEP 30 - Azure: Cosmos DB account (control plane)"); STEP 31 - Azure: Cosmos DB database/container (control plane)", STEP 32 - Azure: Cosmos DB RBAC", STEP 33 - Azure: Cosmos DB key -> Key Vault", STEP 34 - Azure: Cosmos DB section", STEP 35 -Azure: Delete Cosmos DB account", STEP 36 - Azure: Delete storage account", STEP 37 - Azure: Delete Service Bus namespace", STEP 38 - Elapsed wall-clock time for the custom code section only."); STEP 39 - TODO: Log run results off this machine."); STEP 40 - Print end-of-run memory and disk deltas vs. the snapshot."); STEP 41 - Total elapsed wall-clock time since program start.");
cargo install cargo-modules cargo-call-stack ctags universal-ctags rust-code-analysis-cli
cargo modules generate graph --bin azure-rust 2>&1 | head -100
cargo modules dependencies --bin azure-rust --no-modules --no-types --no-traits --no-externs --no-sysroot 2>&1 | head -150
It takes time to define tests and run code coverage (identifying what portions of the codebase passes quality checks). But automation can help.
rustup component add llvm-tools-preview
cargo install cargo-llvm-cov
Installing /Users/johndoe/.cargo/bin/cargo-llvm-cov Installed package `cargo-llvm-cov v0.8.7` (executable `cargo-llvm-cov`)
cargo llvm-cov --help
That command explains how to upload code coverage metrics to popular reporting services like Codecov or Coveralls.io.
test result: ok. 20 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.21s Filename Regions Missed Regions Cover Functions Missed Functions Executed Lines Missed Lines Cover Branches Missed Branches Cover -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- /Users/johndoe/bomonike/rustlang-samples/src/csv2rag/src/main.rs 1320 155 88.26% 72 1 98.61% 741 69 90.69% 0 0 - -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- TOTAL 1320 155 88.26% 72 1 98.61% 741 69 90.69% 0 0 -
To run code coverage within this sample GitHub Action .yml:
coverage:
name: Code coverage
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Install the Rust toolchain
uses: actions-rust-lang/setup-rust-toolchain@v1
with:
components: llvm-tools-preview
- name: Install cargo-llvm-cov
uses: taiki-e/install-action@cargo-llvm-cov
- name: Generate code coverage
run: cargo llvm-cov --all-features --workspace --lcov --output-path lcov.info
- name: Generate report
run: cargo llvm-cov report --html --output-dir coverage
- uses: actions/upload-artifact@v4
with:
name: "Coverage report"
path: coverage/
# clone Rust-Algorithms as a peer of
cd /Users/johndoe/github-wilsonmar/rustlang-samples/src
git clone https://github.com/wilsonmar/Rust-algorithms.git Rust-algorithms 2>&1 | tail -20
echo "---"
ls /Users/johndoe/github-wilsonmar/rustlang-samples/src
QUESTION: How to call functions in the Algorithms repo?
This may be a popular trivia question that everyone may not know:
VIDEO Rust cannot handle double-linked lists, aka self-referential structs and cyclic graphs.
The workaround is the Arena Pattern which has a 36% performance penalty to maintain the sequence number.
VIDEO: Modern All Rust Stack - Dioxus, Axum, Warp CLI, SurrealDB to create a Notebook app running on a web browser.
Qdrant vector database for semantic search
VIDEO: Unlike web apps using Electron, Rust Tauri or Iced or Floem,
VIDEO: Rust uses WGPU layer, a cross-platform abstraction for backends Vulkan, Metal, DirectX on Windows. That allows manipulatio of Floem and Makepath directly on the GPU. So Rust runs fundamentally faster bypassing the DOM and CSS engine (the most expensive part).
VIDEO: Why WASM? It runs in a sealed sandbox. 16 GB on browser. A WASM module is just code, not like a Docker container which contains a whole operating system like Ubuntu. So it starts in 1ms vs 300ms. Thus, Akamai bought Fermyon (serverless WASM). Sopify swapping containers for WASM. However, JavaScript still boots the app, fetches .wasm, paints every pixel.
kubectl apply -f wasm-workload.yaml
Dioxus WASM for browser
rustup target add wasm32-unknown-unknown
rust-std installed
cargo install dioxus-cli
https://www.youtube.com/shorts/fpcS7kifs1I
dx new hello-dioxus
cd hello-dioxus
ls # assets
cargo add dioxus # core
cargo add dioxus-web # renderer
.cargo/config.toml
[profile.release]
opt-level = "z"
lto = true
codegen-units = 1
panic = "abort"
strip = true
dx --help
Execute a binary from npm or jsr, like npx
https://dioxuslabs.com/learn/0.4/getting_started/wasm/?phantom=usage#usage
dx serve --hot-reload
dx serve --platform web --release # For a more optimized build (crucial for smaller WASM binaries)
Why? Rust is the lowest-cost language to use on AWS Lambda service.
https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/rustv1/run_all.sh
Rust on AWS use tracing_subscriber with env_filter to print information about various information as the example runs. Because the AWS SDK for Rust and many crates used in these examples use tracing for structured logging, it is important to have an understanding of the RUST_LOG variable.
RUST_LOG controls the tracing environment logger level, allowing fine-tuned control of what log messages to display.
Environment variables:
Environment variables specify how Instance Metadata Service (IMDS) provides data about your instance when using the AWS SDK for Rust running in Amazon EC2. See AWS SDKs and Tools - IMDS Credentials
Environment variables are specific to the AWS SDK for Rust.
https://docs.aws.amazon.com/AmazonECR/latest/userguide/what-is-ecr.html Docker image
Tutorial: 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:
IAM - Control access with roles, policies, and permissions.
Auto Scaling Groups - Automatically scale compute up or down.
SNS - Publish/subscribe messaging for alerts and notifications.
{
"email": "test@test.com",
"reputation": "high",
"suspicious": false,
"malicious": false,
"credentials_leaked": true,
"data_breaches": ["LinkedIn", "Adobe"],
"first_seen": "2015-01-01",
"last_seen": "2023-10-24"
}
WhoCalled.us: One of the oldest and most straightforward databases. Just type in the number to see comments from other people who received calls from it.
800Notes.com: Highly active forum-style site. You type in the number and read a thread of comments from other users detailing exactly what the scammer said or wanted.
ShouldIAnswer.com: Originally a popular app, their website (shouldianswer.com) allows you to search numbers and see a “trust rating” based on community feedback.
RoboKiller Lookup: RoboKiller is a major spam-blocking app, but they have a free web lookup tool where you can type in a number to see if it’s in their scam database.
https://github.com/grafana/pyroscope-rs/blob/main/build.rs profile
v038 whereis @rustops.md created 2021-10-03