rust
35 lines · 1 tab
Marcus Chen
Jan 2026
1 tab
pub struct Server {
host: String,
port: u16,
workers: usize,
}
pub struct ServerBuilder {
host: Option<String>,
port: Option<u16>,
workers: usize,
}
impl ServerBuilder {
pub fn new() -> Self {
Self { host: None, port: None, workers: 4 }
}
pub fn host(mut self, host: String) -> Self {
self.host = Some(host);
self
}
pub fn port(mut self, port: u16) -> Self {
self.port = Some(port);
self
}
pub fn build(self) -> Result<Server, &'static str> {
Ok(Server {
host: self.host.ok_or("host is required")?,
port: self.port.ok_or("port is required")?,
workers: self.workers,
})
}
}
1 file · rust
Explain with highlit
For structs with many optional fields, the builder pattern provides a fluent API for construction. I define a separate Builder struct with methods that return self for chaining. The final build() method validates and returns the target struct. This is more ergonomic than constructors with many arguments, and it allows validation logic (required fields, invariants). The derive_builder crate can auto-generate builders, but for complex cases I write them manually. I use builders for config structs, clients with many options, and anywhere you'd use optional named parameters in other languages. The pattern also makes it easy to add new fields without breaking existing code, improving API stability.
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.