Need the longest string in a Vec? You don't need a fold:
let longest = words.iter().fold(None, |b, w| match b {
Some(x) if x.len() >= w.len() => b,
_ => Some(w),
});
Just write:
let longest = words.iter().max_by_key(|w| w.len());
#rustlang
Every Rust codebase has this somewhere:
let v = raw.max(0).min(100);
You stop, squint, work out which bound is which.
Just write what you mean:
let v = raw.clamp(0, 100);
Works on any Ord — ints, floats, chars, your own types.
#rustlang
Filtering a sorted BTreeMap by a key range walks every entry just to throw most away.
BTreeMap::range seeks to the window in O(log n), then iterates only what you asked for. Works with `a..b`, `a..=b`, `..b`, and `a..`.
#rustlang
Got an Option<String> and a function that wants Option<&str>?
Stop writing .as_ref().map(|s| s.as_str()).
.as_deref() does it in one call — and works for Option<Vec<T>>, Option<Box<T>>, anything that derefs.
#rustlang
Your `Option<u32>` is 8 bytes when it could be 4.
`NonZeroU32` swaps `u32`'s zero bit pattern out for the `None` discriminant. Same info, half the size — and the compiler enforces "not zero" for free. Wrap your IDs in one.
#rustlang
Wrap an assert in a helper, and every failure blames the helper's line — useless across 50 tests.
#[track_caller] on the helper makes the panic point at the *caller* instead. That's how assert!, unwrap, and expect already work.
#rustlang
`assert!(matches!(x, Foo::Bar))` fails with… "assertion failed: matches!(x, Foo::Bar)". Cool. Was x what? Rust 1.96 stabilises `assert_matches!` — same one-liner, panic message now prints the actual value alongside the pattern.
#rustlang
Sorting by multiple fields in Rust with a nested if/else tie-break ladder is brutal to read.
Ordering::then_with chains comparators top-down in priority order. No nesting. Wrap a field in Reverse to flip that key's direction.
#rustlang
"Just check if it exists first" — and that's how lockfiles get clobbered.
`File::create_new(path)` is the atomic version. `O_CREAT | O_EXCL` under the hood, `AlreadyExists` if you lost the race.
#rustlang
Smearing `.saturating_add()` and `.saturating_sub()` across every line of arithmetic gets old fast.
Wrap the value in `std::num::Saturating<T>` once and `+`, `-`, `*`, `+=` all clamp to MIN/MAX instead of wrapping or panicking.
#rustlang
`*map.entry(k).or_insert(0) += 1` is fine for counters — until first-time entries need different data than updates.
`Entry::and_modify` runs on hit, `or_insert` runs on miss. Chain them. One lookup, two branches.
#rustlang
Returning Cow<str> but always cloning inside the function? You're paying for Cow with none of the benefit.
Cow::to_mut() does the lazy work for you: flips borrowed → owned only when something actually changes, then it's a free &mut String after.
#rustlang
Pain: async futures keep pointers into their own locals. Move one mid-poll and you've earned UB.
Pin<P> is the type that says "this value won't move." Future::poll takes Pin<&mut Self>; the pin! macro pins on the stack, Box::pin pins on the heap.
#rustlang
Pain: an Rc cycle leaks every node — strong-counts never hit zero, so drop never runs.
Fix: make the back-edge Weak. Rc::downgrade gives a non-owning pointer; upgrade() returns Option<Rc<T>>: "if it's still alive."
#rustlang
Eight threads, one counter, zero data races.
Arc<Mutex<T>> is the workhorse of shared mutable state in Rust: Arc gives each thread its own pointer to the same heap allocation, the Mutex makes the writes safe. Drop either half and it doesn't compile.
#rustlang
One value. Two parts of your code want to own it. Cloning doubles memory. Lifetimes turn into a 6-type cascade.
Rc<T> gives shared ownership in one line. Each Rc::clone is a counter bump, not a copy. Last owner out drops the value.
#rustlang
Still adding `lazy_static = "1"` to Cargo.toml for one config map?
Since Rust 1.80, `std::sync::LazyLock` does the same job — no macro, no crate, just a normal `static`. And `OnceLock` covers the "set it later from runtime data" case.
#rustlang
Wrapping `Arc<Mutex<u64>>` around a hit counter so `n += 1` works across threads?
The CPU has a single instruction for that. `Arc<AtomicU64>` + `fetch_add(1, Relaxed)`. Lock-free, no guard, no `unwrap`.
#rustlang
8 threads only want to read your config. With Mutex, they line up one at a time.
RwLock<T> splits the door: many readers OR one writer. Read-heavy workloads actually fan out in parallel.
#rustlang
6K Followers 1K FollowingLove computers and coding.
While I'm particularly passionate about Rust,it's not the only language I work with.
Recently started loving embedded programming
16K Followers 1K FollowingRust / backend dev / org design / climate. Baking on the good days.
Author of https://t.co/WDxzUHAAe6.
Building https://t.co/YMfw1oaHIi, a new Rust web framework.
397K Followers 0 FollowingLove Linux/Unix, open source, and programming? Into Sysadmin & DevOps? Follow us! Boost your IT career with daily new tools, apps, and humor ⤵️
291K Followers 563 FollowingCo-Founder of ByteByteGo | Author of the bestselling book series: ‘System Design Interview’ | YouTube: https://t.co/9gPSJSrtPU
593 Followers 2 FollowingRetweets any tweet tagged with #rustlang. Lightly curated to remove spam. You can view my Rust source code at https://t.co/TwhMNhBAJj.
36K Followers 189 FollowingRust live-coder and OSS tinkerer who loves teaching. I try to keep a high SNR. Wrote Rust for Rustaceans. At @HelsingAI. Ex AWS. Co-founded @readysetio. he/him
153K Followers 2 FollowingA programming language empowering everyone to build reliable and efficient software.
** This account is no longer active. Follow us on other platforms! **