Rust
Programming Language
Links
Rust is what C++ should have been,
had it not escaped Bell Labs prematurely
Updated: 5 November 2024
Learn Rust
Of course, begin with resources on the Rust programming language website:
https://rust-lang.org/
There is a handy cheat sheet (and
A (type-based) Rust cheatsheet),
and
SVG poster
in addition to
The Rust Language Reference
and
The Rust Language Grammar.
Both continue as works-in-progress 3 years after 1.0-stable (released May
2015) with pull-requests or filing issues welcomed:
reference or
grammar.md,
respectively.
Coming from C/C++?
Learn Rust the Dangerous Way.
Reference to the Rust Standard Library, run:
rustup doc --std
Similarly, for the de facto tutorial,
TRPL (2nd Ed), run:
rustup doc --book
While there’s much to appreciate and respect about it, its style may seem
verbose for some.
Now, there’s an abridged 3600 word version:
Summary of The Rust Book,
which addresses the critique below.
The mainline edition of The Rust Book is a work-in-progress despite
having a couple of dead-tree versions.
Critique:
In technical writing, conventional practice introduces new material by
directly stating the most novel concepts for the audience first, followed
by elaboration and examples.
By contrast, TRPL 1st and 2nd Edition use a narrative flow typical of many
bloggers, where there’s a build-up of anticipation followed by a reveal of
substance. The single most useful sentence– or sometimes, phrase– within
each section stating the actual idiom often gets lost within their
storytelling style.
Bridging such differences: they would do well by highlighting language
idioms in a sidebar (or just a bold font, inline) for each subsection.
This would preserve integrity of their writing style while accommodating
both a more diverse audience and readers returning to find just the one
tidbit of interest.
For those who grew up with the likes of
K&R C
lovingly within reach, there is another book a bit closer, in that it states
an idiom first and then its companion example or explanation:
Highly recommended book:
Programming Rust, 2nd Ed.
- Blandy, Jim; Orendorff, Jason; Tindall, Leonora
- O'Reilly Media
- Second edition: June 2021 (first edition: December 2017)
- Available as DRM-free PDF from ebooks.com,
readable via generic PDF readers; i.e., opens fine on Linux
(No affiliation with the authors, publisher or sellers)
For both 1st & 2nd Editions:
Blandy’s & Orendorff’s Programming Rust is the closest to a K&R C book
for the Rust programming language so far.
It’s concise. It begins with the key concepts. It’s organized suitably
for the pragmatic software developer with a dev-ops mindset.
For working through actual code, the canonical book for that is:
Rust by Example (RBE).
Discuss on Discord. (Since the official
Mozilla IRC service has been sunset, there is an unofficial
#rust on Freenode.)
Stay Current
Rust Search Extension – browser extensions:
“Search docs, crates, builtin attributes, official books, and error codes,
etc in your address bar instantly. Input keyword rs then press Space to get started.”
This Week In Rust
Follow Rust programming language and community updates. Reading just this
one is likely enough for most people, as they aggregate all of the other
major resources.
Official blog
Announcements on
The Rust Programming Language Forum
Track possible/pending features within
The Unstable Book, but note that
many items in there may never reach stable
. Also, remember to annotate any code using these features with: #![feature(foo_feature)]
.
Likely to be covered on one of the above websites when it’s news, but complete collection of confirmed vulnerable exploits:
RustSec advisory-db
Attend Rust Conf or Rust Belt Rust. Follow conf activity via
Twitter #rustconf or
IRC #rustconf.
Stay current but not necessarily too current:
- Consider cargo-msrv
- “Find the minimum supported Rust version (MSRV) for your project”
cargo
subcommand
Employment
These yielded solid leads and jobs for the maintainer of this list:
Others for which the maintainer of this list has no direct experience:
Overcome & Persevere
Certain language features are challenging even for those who may believe
they’ve grasped the core concepts.
Here are some resources found to be helpful.
If Rust has a golden rule, consider it being “Whenever the body of a
function contradicts the function’s signature, the signature takes
precedence; the signature is right and the body is wrong.” This gets
explained with more detail and examples in
Steve Klabnik’s 2023 posting.
Beware of silent integer overflows:
Instead of operators like a + b * c
, use methods like
.checked_add().
For instance, let mut x:u8=255; x+=100;
produces difference behaviour when
compiled via cargo build
with and without --release
flag. It will panic
without the flag, and silently overflow/wrap-around with the release
flag. This is because the default case suits the fast path for low-level
hardware. There is virtually no additional overhead for these methods, when
examining the generated Assembly language code.
Alternatively, use a BigNum library
such as one built upon GNU Multiple Precision (GMP)
like gmp-mpfr-sys
or “a big integer library with good performance,” ibig-rs.
Introduction to the mindset used by Rust:
Rust Means Never Having to Close a Socket
from pre-1.0 Rust (Oct 2014) yet still relevant with newer editions for concepts explained.
Be sure to also read at least the introductory chapters of
The Rustonomicon, even if you have no
intention of ever using unsafe
code. Explanations given there provide a
more diverse perspective on ownership, borrowing,
lifetimes,
variance
(Vlad’s answer may help explain concepts behind the jargon),
drop check, etc.
Inside Rust Blog
Selection of forum posts, such as from
Stack Overflow
and Reddit:
A catalogue of Rust design patterns
Even for those coming from one of the Lisp languages/dialects and agree with
Rich Hickey that patterns mean you’ve “run out of language,” this list is
still quite valuable. (And yes, Rust has robust Macros that accommodate
many of the use cases for which Common Lisp macros are actually used.)
Podcasts:
Concurrency without Tokio
- mio
- Metal I/O library for Rust
- “Mio is a fast, low-level I/O library for Rust focusing on non-blocking
APIs and event notification for building high performance I/O apps with
as little overhead as possible over the OS abstractions.”
- since early days of Rust and actively maintained
- io_uring
Tokio
An event-driven, non-blocking I/O platform for writing asynchronous I/O backed applications:
Noteworthy perspective:
- Async Rust can be a pleasure to work with (without
Send + Sync + 'static
)
- Quotes a paper published in 2016:
Not all use cases would see increased performance from a
single-threaded design, but the paper
Scalability! But at what COST?
suggests that single-threaded implementations may perform better than
parallelized ones for many more algorithms than people might commonly
think.
- I wholeheartedly agree, having built high-concurrency libraries in
ANSI C, C99, the despicable child of C, Common Lisp, and (if you
squint hard enough) Python (after which I largely abandoned the language
in favor of CL, but I digress…), and made heavy use of Erlang/OTP’s
gen_server with its strict trade-offs for parallelism
for which Erlang’s concurrency is worth understanding in this context.
- The technique I used focused on dispatch of feeding workers:
- Give ownership of a prioritized short queue to each worker–
definitely owned, not borrowed– which requires copy as Erlang
does for CPU cache coherence and (generally) improves overall throughput.
- Continually analyze performance for tuning the dispatcher– albeit
“performance” is relative and a moving target.
- Update after a representative sample with either statistically
significant or inconclusive results.
- Repeat early & often.
- Bonus points for tuning without stop/start, and CL’s runtime
compilation excelled there.
- This accommodated dispatchers with different priorities based upon
nominal traffic, multi time zone peaks, and intentional degrading
quality-of-service (e.g., brown-out).
Futures, async/await
See The Async Book
(and GitHub repo)
As of Rust v1.39 (November 2019),
async/await landed
in stable
.
Achieve high concurrency with Rust using far more workers than total number
of OS heavyweight threads or physical CPU cores.
Rust accommodates Futures without additional runtime overhead (unlike
“green threads”).
Older links that may be removed soon:
- Read about Romio,
which ported a subset of Tokio to newer async/await and led to
an enhancement
within futures-rs along the way!
- Albeit, as of mid-December 2018, it’s still not yet a complete replacement.
- “We intend to have the same
rapid, ‘nightly-style’ release cycle with romio as futures 0.3 currently
has.”
- See Fahrenheit as a “toy” use
of futures-rs 0.3 and continues being maintained:
- See blog post for its documentation and
overview
- Beware that Fahrenheit uses POSIX
select(2)
system-call. For those
using FreeBSD, use kqueue(2)/kevent(2)
, and for Linux, use epoll(7)
for non-trivial use cases.
- Sample code using attributes (not language keywords yet) appears within
the README of:
futures-await
- Per issue 108,
feature
flags require some editing in order to compile with Nightly as
of 2018-07-27 and further changes as of at least 2018-09-02
- With those changes applied, sample code confirmed to build and run using:
rustc 1.31.0-nightly (2bd5993ca 2018-10-02)
- From the Rust Conf 2018 Async/Await Class:
- Presentation
and repo
- Code stubs require
fixes since Rust Conf:
- Replace
use std::mem::PinMut
with use std::pin::PinMut
in *.rs
- See
Spawn trait
which gets mentioned in presentation without being linked
- Newer syntax pertaining to async/await have made it into Nightly,
and some features/syntax may change further in future
WASM
For hand-written Rust, JavaScript and HTML, consider starting with
bare metal WASM
rather than messing with the entire tooling of wasm-pack, wasm-bindgen,
webpack and npm to produce a Rust-powered webpage every time.
WebAssembly:
For building webapps, start with rust-webpack-template.
For building libraries, start with
wasm-pack-template.
Alternatively, MiniWASM is
“a minimalist Rust WebAssembly project template” that was created for
“projects that have more strict performance requirements” than
wasm-bindgen
.
Tooling, Runtimes & Edge Computing:
- stdweb – “Expose a full suite of Web
APIs as exposed by web browsers” as a library (not a framework)
- Yew – “a modern Rust framework
inspired by Elm and ReactJS for creating multi-threaded frontend apps with
WebAssembly”
- wasmtime -
“A small and efficient runtime for WebAssembly & WASI”
- GitHub repo
- From Bytecode Alliance -
“open source community dedicated to creating secure new software foundations, building on standards such as WebAssembly and WebAssembly System Interface (WASI)”
- Lucet – Sandboxing WebAssembly Compiler
- Wrangler -
“a CLI tool designed for folks who are interested in using Cloudflare Workers”
- wasmer – “Build Once, Run Anywhere.
Universal Binaries powered by WebAssembly”
- Running WebAssembly on AWS Lambda
- Look, Ma! No JS! - Compiling Rust to WebAssembly
Also:
Web Dev
- Building a Website Using Rust, Rocket, Diesel, and Askama
- Starting before Edition 2018, we used something close to this pattern
with success at a startup
- Rust-stable, pre-1.0 Actix-web, Diesel and Handlebars for trivial templating
- We passed on Rocket because it required Rust-Nightly
(as of 2021-04-22, no released version accommodates Rust stable)
- Template functionality actually used there was on par with
askama;
i.e., without using conditional or loop syntax
- via Diesel, PostgreSQL JSONB fields were used as ad hoc Materialized
Views for read-optimized circular work-flow:
i.e., read, write, query to regenerate JSON, write that to JSONB and
cache it
- Premise adopted from prior Common Lisp usage in high-performance
scenarios:
Why do at run-time that which can be done at compile-time or load-time?
- Functionality was comparable to Medium.com but with security priorities
necessary for fin-tech
(It’s worth noting that having “finance” or “fin” in your domain name,
you might as well paint a target on your back. Direct and side-channel
attack vectors that may be ignored by other types of businesses must be
hardened. Thus, Rust!)
- That effort was one person from concept to soft launch within six months,
with a senior-level then junior-level doing UI/styling
- Today, it would be well under half that time since tooling has matured
(assuming a healthier startup environment, but I digress…)
- https://matej.laitl.cz/bench-actix-rocket/
- Lessons learned on writing web applications completely in Rust
- Wiki - An Opinionated Guide To Rust Web Servers
- hyper-ish 2021 in review
- Replacing nginx with axum
Data Modeling
Data Storage
- Noria -
Dynamically changing, partially-stateful data-flow for web application backends
- evmap -
A lock-free, eventually consistent, concurrent multi-value map
- Like Noria, implements even/odd Epoch counters implying state for
lock-free, multiple-readers single-writer
Interacting With Other Languages
Rust calling other languages:
Rust embedded into other languages:
Rust calling into the Dalvik / JVM:
Robustness
Ensure cancel-safety where appropriate.
Essentially, avoid losing data that has already been queued
which also applies to Mutex.
This is an advanced topic; however:
- Straight-forward modification to critical-path Rust code
- e.g., modifying shared structs or queues
- Ensure robust systems through determinism
Essentially, migrate away from queue.push(foo).await
to
quque.reserve().await.push(foo)
but also understand why.
See tokio’s reserve().
See also just this one small section, and optionally read the whole article
if thirsty for more:
async fn is an inversion of control
Embedded Systems
- Ferrocene
- Previously called
Sealed Rust
- “Ferrocene will provide a qualified Rust compiler tool chain. With this,
Ferrous Systems will make Rust a first-class language for
mission-critical and functional safety systems.”
- Ferrocene (as of early 2023) will be “an ISO26262 qualified version of
the existing open-source compiler, rustc. Ferrocene will be first made
available to customers in the ISO 26262 space, with others like DO-178C,
IEC 61508 and IEC 62278 in mind.”
- Tiny Rocket - James Munns - reducing size of Rust runtime executables
- Knurling
- “Get a handle on bare metal Rust”
- rustysd
- “A service manager that is able to run "traditional” systemd services,
written in rust"
- “tries to replicate systemd behaviour for a subset of the configuration
possibilities”
Advocacy & Comparisons
Rust in production:
Surveys, etc.
A survey of programming languages illustrates that each serves
different purposes: https://stackshare.io/stackups/python-vs-ruby-vs-rust
Code Editors
Rust-stable includes rust-analyzer,
an implementation of Language Server Protocol (LSP).
See Emacs section
within rust-analyzer manual.
Also consider:
Visual Studio Code
For non-Emacs heathens out there…
RLS
Rust-stable includes rust-analyzer
which supersedes rls
.
Links
From the official websites and repos:
Search packages, and read their documentation:
- crates.io - Official site to browse Rust crates
- lib.rs - A fast, lightweight, site to browse Rust crates
- “An alternative opinionated front-end to crates.io”
- With more features such as relative ranking of each crate in multiple
categories
- 4 June 2018 announcement for crates.rs (which forwards to lib.rs)
Forum, IRC Channels and more are linked from Community page.
Academic Publications:
Helpful For Understanding
In no particular order:
Runtime Profiling
Error-Handling
As of late 2022, a bit of consensus pointed to simply using:
Older articles:
Interesting Libraries, Frameworks & Packages
- trending Rust repositories
- Command-Line Argument Parser
- generational-arena
- “A safe arena allocator that allows deletion without suffering from
the ABA problem by using generational indices”
- Noria – “streaming data-flow system
designed to act as a fast storage backend for read-heavy web applications
based on this paper from
OSDI'18”
- clap
- structopt – “Parse command line
argument by defining a struct” with fine-grained expressiveness
- clapme – “Parse command line
arguments by defining a struct. It combines clap with custom derive.”
Based upon DRY principles, as minimalist alternative to
structopt
.
- shrust – “to create interactive
command line shells”
- Rust for NGINX – call Rust from Nginx
- As of their 0.1.1 release for rustc 1.26, still requires C stub code
- Ammonia – a whitelist-based HTML
sanitizing library
- crossterm
- unicode-normalization
- deunicode
- encoding_rs
- ucd – implements 100 properties of the Unicode Character Database
- safe
- “A
#[safe]
attribute for explaining why unsafe { ... }
is OK.”
- bastion
- Fault-tolerant Runtime for Rust applications; detect panics; serves a runtime to prevent abrupt exits; continue serving in case of a failure; select your own recovery scenario; scale workers; define a whole application on top of it
- A Rust answer to Erlang’s “Let it Crash”, perhaps
- bstr - A string type for Rust that is not required to be valid UTF-8
- R1CS - “for building R1CS gadgets, which are useful in SNARKs and other argument systems”
- Cloudflare workers…
- weld - Fast parallel code generation for data analytics frameworks
- Rusoto is an AWS SDK for Rust.
- slab - Pre-allocated storage for a uniform data type
- rust-analyzer - an alternate compiler front-end intended for IDEs and developer work-flow such as incremental compilation
- rust-embedded/cross - “Zero setup” cross
compilation and “cross testing” of Rust crates without messing with your
existing installation
- Elasticsearch Rust Client
- xsv –
fast CSV command line toolkit capable of indexing and joins on very large files
- ripgrep –
recursively searches directories for a regex pattern
See also:
Unsorted Links
Plucked from the ‘net, most are offered without context or explanation but
probably seen on This Week in Rust. Newer items are usually added to the
bottom of this list unless releavant as bullet point under an existing item.
(Tokio related links have been relocated to their own section
above.)
- State of Machine Learning in Rust
- Are we learning yet?
- Python vs Rust for Neural Networks
- Metal IO
- mpi - Rust - message passing interface
- iron - Rust
- The Rise of Rust in Dev/Ops - Mesosphere
- Metaswitch Swagger Codegen for Rust accepted upstream
- Logging in production : rust
- tantivy - full-text search engine library inspired by Lucene and written in Rust
- actix - Actor framework for Rust
- Are we game yet?
- Recommending books (with Rust)
- Rust concurrency patterns: Natural Born Pipelines
- Programming Servo: the makings of a task-queue
- RustConf 2018 Closing Keynote – blog post edition
- Multithreading Rust and Wasm
- On dealing with owning and borrowing in public interfaces
- Compile Time Feature Flags in Rust
- Storing unboxed trait objects in Rust
- Rust asynchronous IO: from mio to coroutine
- osaka – async for rust without the noise –
with blog post
- Calling Rust from iOS
- older: Rust on iOS and
Rust on Android
- see also Native Android app with Kotlin &
Rust on GitLab
- Use Rust for common core Library and Swift & Kotlin for native UI,
and Google officially recommends Kotlin over Java for Android as of May 2019
- Kotlin is what Guy Steele might have delivered, had he arrived to fix Java when it was still called Oak (but thankfully he finished ANSI Common Lisp first)
- Custom Exit Status Codes with ? in main
- cargo-kcov – subcommand for
cargo
to generate HTML code coverage reports
- Add scoped threads to the standard library #2647
- remacs – rewriting C bits as Rust within Emacs
- Snips Open Sources Tract: A Rust Neural Network library for the Edge
- A guide to Rust graphics libraries as of 2019
- World’s first private Cargo registry
- Using Rust to Scale Elixir for 11 Million Concurrent Users
- Rusts hidden talents speeding up builds and managing versions
- i.e., set Rust version or toolchain per project; configure a global
build cache; etc.
- The Typestate Pattern in Rust
- Speedy Desktop Apps With GTK and Rust
- realworld - clone of Medium.com with different language combinations for front-end vs back-end
- Also look at current and recently closed issues, as there are additional code samples than what might be currently posted
- rustgo: calling Rust from Go with near-zero overhead
- “it’s targeting functions that would otherwise be written in assembly: they’d have to be quick (not to undermine the scheduler) and non-recursive (not to blow the stack). For just calling larger Rust functions, one can use cgo”
- Rust GUI ecosystem overview
- Semantic validation in Rust
- “…validate complex data structures at runtime…”
which may be of interest to CLOS and MOP heads
- “Fe2O3 is the chemical formula of Rust”
- “Rusting is a chemical reaction of iron in the presence of oxygen.
Common sheet metal rusting in dry air works like this: 4 Fe + 3 O2 –> 2 Fe2O3.
This reaction is relatively slow and produces a thin coating of stable iron oxide Fe2O3, which is (technically) rust, but is a fairly benign form of rust.” –Linux.Fe2O3: a Rust virus
- Various libraries from Embark Studios such as:
- Quantum computing in Rust, Part 1
- Note: following a critique
of Part 1, the author noted that the article series is in part his
learning path on Quantum Computing, so anticipate revisions and
corrections in subsequent installments
- Tiny Windows executable in Rust
- The Common Rust Traits
- Interior mutability patterns
- A Thought Experiment: Using the ECS Pattern Outside of Game Engines
- Packaging a Rust project for Debian
- Returning Trait Objects
- Cheap tricks for high-performance Rust
- Oxidize Conference
- Hyper traps -
handling panics and using async closures
- Avoid Build Cache Bloat By Sweeping Away Artifacts
- A Few Github Action “Recipes” for Rust
- https://deislabs.io/posts/a-fistful-of-states/
- https://fasterthanli.me/articles/so-you-want-to-live-reload-rust
- Handling Unix Kill Signals in Rust
- Black Hat Rust
book:
- “Deep dive into offensive security with the Rust programming
language. PDF, Kindle & Epub”
- Fluvio – Programmable platform for data in motion
- “A real-time data streaming platform with in-line computation
capabilities. Use Fluvio SmartStreams to upload your custom logic and
modify data as it moves over the network.”
- repo
- news
- 15k inserts/s with Rust and SQLite
- qcell
- Statically-checked alternatives to RefCell
- graph
- “A library that provides a collection of high-performant graph
algorithms.
This crate builds on top of the
graph_builder crate,
which can be used as a building block for custom graph algorithms.”
- meilisearch
- “A lightning-fast search engine that fits effortlessly into your apps,
websites, and workflow.”
- videocall-rs
- teleconference system written in rust
- Demo requires Chrome or Chromium based browsers
because instructions require adding server IP address to this list:
chrome://flags/#unsafely-treat-insecure-origin-as-secure
- secrecy
- … provides wrapper types and traits for secret management in Rust, namely the
Secret<T>
type for wrapping another value in a “secret cell” which attempts to limit exposure (only available through a special ExposeSecret
trait)
- This helps to ensure secrets aren’t accidentally copied, logged, or otherwise exposed (as much as possible)
- Ensures secrets are securely wiped from memory when dropped
- cargo-deny
- cargo plugin to lint project dependency graph as assurance that dependencies conform to expectations and requirements
- The beauty of a Rust message processor
- i.e., classify errors as either recoverable or unrecoverable
- Fully Automated Releases for Rust Projects
- Destructing trees safely and cheaply
- Building Async I/O in Rust: How Futures, Wakers, and Thread Pools Work Together
- Serde for trait objects
- First in a series
- “Remark: If you are in a situation where you want to serialize a trait
object, please take a step back. Check if you can replace your trait
object with an enum. In my experience, the enum approach is much easier
to work with.”
- See also: typetag — Serde
serializable and deserializable trait objects
- Best Practices for Derive Macro Attributes in Rust
See Also
- Carp Language
- A statically typed Lisp, without a GC, for real-time applications
- Some language criteria are similar to Rust’s
- What if something like Carp becomes the AST for Rust…?
Maintainer Notes
This page is a perpetual work-in-progress.
It should have begun life within a code repo, but this is what we have…
Most updates here since 2018 were gleaned from
This Week In Rust. Other content since
2015 came from the various lists and fora mentioned in
Stay Current above.