0 day streak
Code library

Code worth reading.

Hand-picked snippets across TypeScript, Python, Rust, Go, and more — each one comes with a line-by-line breakdown so you can read it like the people who wrote it.

3495 snippets · 10 languages
▶ Start learning
Rust · IntermediateSnippet

Functional Iterator Adapters

Iterators in Rust are lazy and powerful. 'filter' and 'map' allow for functional-style data transformation without unnecessary intermediate allocations.

snippet.rs
rust
1
2
3
4
5
let numbers = vec![1, 2, 3, 4, 5];
let doubled_evens: Vec<i32> = numbers.iter()
.filter(|&x| x % 2 == 0)
.map(|x| x * 2)
.collect();
PerformanceBest Practices
Rust · IntermediateSnippet

Generic Bounds with Traits

Generic bounds allow you to restrict a generic type so that it must implement specific behaviors (traits). This ensures the function can call the required methods safely.

snippet.rs
rust
1
2
3
4
5
6
7
trait Summary {
fn summarize(&self) -> String;
}
fn notify<T: Summary>(item: &T) {
println!("Breaking news: {}", item.summarize());
}
SyntaxFunctions
Rust · IntermediateSnippet

Enums with Data and Pattern Matching

Rust enums are algebraic data types. They can store different types of data in each variant, which can be elegantly extracted using 'match'.

snippet.rs
rust
1
2
3
4
5
6
7
8
9
10
11
12
13
enum WebEvent {
PageLoad,
KeyPress(char),
Click { x: i64, y: i64 },
}
fn inspect(event: WebEvent) {
match event {
WebEvent::PageLoad => println!("page loaded"),
WebEvent::KeyPress(c) => println!("pressed '{}'", c),
WebEvent::Click { x, y } => println!("clicked at {}, {}", x, y),
}
}
SyntaxData Types
Rust · IntermediateSnippet

Error Propagation with the ? Operator

The '?' operator is a concise way to handle errors. If a Result is an Err, it returns early from the function with that error; otherwise, it unwraps the Ok value.

snippet.rs
rust
1
2
3
4
5
6
7
8
9
use std::fs::File;
use std::io::{self, Read};
fn read_username() -> Result<String, io::Error> {
let mut f = File::open("hello.txt")?;
let mut s = String::new();
f.read_to_string(&mut s)?;
Ok(s)
}
Error HandlingControl Flow
Rust · IntermediateSnippet

Basic Lifetime Annotations

Lifetimes ensure that references remain valid as long as they are needed. Annotating a struct with '<'a>' tells the compiler the struct cannot outlive the reference it holds.

snippet.rs
rust
1
2
3
4
5
6
7
8
struct Excerpt<'a> {
part: &'a str,
}
fn main() {
let text = String::from("Rust is fast.");
let first_word = Excerpt { part: &text[0..4] };
}
Memory ManagementSyntax
Rust · IntermediateSnippet

Thread-Safe Shared State with Arc and Mutex

Arc (Atomic Reference Counted) allows multiple threads to own the same data, while Mutex (Mutual Exclusion) ensures that only one thread can mutate the data at a time.

snippet.rs
rust
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
use std::sync::{Arc, Mutex};
use std::thread;
let counter = Arc::new(Mutex::new(0));
let mut handles = vec![];
for _ in 0..10 {
let counter = Arc::clone(&counter);
let handle = thread::spawn(move || {
let mut num = counter.lock().unwrap();
*num += 1;
});
handles.push(handle);
}
for handle in handles { handle.join().unwrap(); }
Memory ManagementFunctions
Rust · IntermediateSnippet

Dereferencing Raw Pointers in Unsafe Rust

Raw pointers (*const T and *mut T) allow you to bypass Rust's ownership and borrowing rules. Dereferencing them is considered unsafe because the compiler cannot guarantee the pointer is valid or that it doesn't violate memory safety.

snippet.rs
rust
1
2
3
4
5
6
7
8
9
let mut num = 5;
let r1 = &num as *const i32;
let r2 = &mut num as *mut i32;
unsafe {
println!("r1 is: {}", *r1);
*r2 = 10;
println!("num is now: {}", num);
}
Memory ManagementSyntax
Rust · IntermediateSnippet

Efficient Map Updates with the Entry API

The Entry API allows you to check for a key's existence and perform an operation in a single step, avoiding double lookups and providing a more expressive way to handle conditional insertion.

snippet.rs
rust
1
2
3
4
5
6
7
8
use std::collections::HashMap;
let mut scores = HashMap::new();
let team = String::from("Blue");
scores.entry(team).and_modify(|e| *e += 10).or_insert(50);
println!("{:?}", scores);
PerformanceFunctions