rust
15 lines · 1 tab
Marcus Chen
Jan 2026
1 tab
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
struct UserId(u32);
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
struct PostId(u32);
fn fetch_user(id: UserId) {
println!("Fetching user {:?}", id);
}
fn main() {
let user_id = UserId(42);
fetch_user(user_id);
// fetch_user(PostId(42)); // ❌ compile error
}
1 file · rust
Explain with highlit
The newtype pattern wraps a primitive in a tuple struct to create a distinct type. This prevents mixing up values that are semantically different but have the same underlying type (like UserId(u32) vs PostId(u32)). The compiler enforces that you can't pass a UserId where a PostId is expected. Derive Debug, Clone, Copy, etc., as needed. For conversions, implement From and Into. I use newtypes extensively in domain modeling to encode business rules in the type system. The cost is zero: the wrapper is optimized away at runtime. This pattern makes APIs safer and self-documenting, and it catches bugs at compile time that would be runtime errors in dynamic languages.
Related snips
ruby
class Post < ApplicationRecord
belongs_to :author, class_name: 'User'
has_many :comments, dependent: :destroy
scope :published, -> { where.not(published_at: nil).where('published_at <= ?', Time.current) }
scope :draft, -> { where(published_at: nil) }
ActiveRecord scopes for reusable query logic
rails
activerecord
patterns
by Alex Kumar
1 tab
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
Share this code
Here's the card — post it anywhere.