rust
15 lines · 1 tab
Marcus Chen
Jan 2026
1 tab
use std::borrow::Cow;
fn ensure_prefix(input: &str) -> Cow<str> {
if input.starts_with("https://") {
Cow::Borrowed(input)
} else {
Cow::Owned(format!("https://{}", input))
}
}
fn main() {
let url1 = ensure_prefix("https://example.com");
let url2 = ensure_prefix("example.com");
println!("{}, {}", url1, url2);
}
1 file · rust
Explain with highlit
Cow<'a, T> (clone on write) holds either a borrowed or owned value. It borrows when possible and clones only when mutation is needed. I use Cow<str> for APIs that might need to modify a string: if no changes are needed, it stays borrowed; if changes are made, it clones. This optimizes the common case (no mutation) while supporting the less common case (mutation). The .to_mut() method clones if needed and returns a mutable reference. Cow is useful for config processing, normalization, and string transformations where most inputs don't need changes. It's a zero-cost abstraction when borrowing and a one-time clone when mutating.
Related snips
rust
struct Config<'a> {
name: &'a str,
value: &'a str,
}
fn parse_config(line: &str) -> Config {
Lifetime annotations for flexible borrowing in structs
rust
lifetimes
borrowing
by Marcus Chen
1 tab
rust
use crossbeam::channel::unbounded;
use std::thread;
fn main() {
let (tx, rx) = unbounded();
Crossbeam for advanced concurrent data structures
rust
concurrency
lock-free
by Marcus Chen
1 tab
rust
use tracing::{info, instrument};
#[instrument]
fn process_request(user_id: u64) {
info!(user_id, "Processing request");
// Work happens here
tracing for structured logging and distributed tracing
rust
observability
tracing
by Marcus Chen
1 tab
rust
use std::sync::mpsc;
use std::thread;
fn main() {
let (tx, rx) = mpsc::channel();
Channels (mpsc) for message passing between threads
rust
concurrency
channels
by Marcus Chen
1 tab
rust
use clap::Parser;
#[derive(Parser, Debug)]
#[command(author, version, about)]
struct Args {
#[arg(short, long)]
clap for CLI argument parsing with derive macros
rust
cli
clap
by Marcus Chen
1 tab
ruby
# BAD: N+1 query problem
@users = User.all
@users.each do |user|
puts user.posts.count # Fires query for each user!
end
ActiveRecord query optimization and N+1 prevention
ruby
rails
activerecord
by Sarah Mitchell
3 tabs
Share this code
Here's the card — post it anywhere.