macro_rules! create_function {
($func_name:ident) => {
fn $func_name() {
println!("Called {}", stringify!($func_name));
}
};
}
create_function!(foo);
create_function!(bar);
fn main() {
foo();
bar();
}
Declarative macros (macro_rules!) let you write code that writes code, reducing boilerplate. They pattern-match on token trees and expand at compile time. I use them for repetitive patterns like implementing traits for multiple types or generating test cases. Macros are hygienic: they don't accidentally capture variables from the calling context. The syntax takes some getting used to ($(...)* for repetition, $var:ty for type arguments), but it's powerful once you learn it. For complex code generation, procedural macros (derive, attribute, function-like) are more flexible but harder to write. I reach for macro_rules! when I need simple repetition and procedural macros when I need to parse attributes or introspect types.
Related snips
struct Config<'a> {
name: &'a str,
value: &'a str,
}
fn parse_config(line: &str) -> Config {
Lifetime annotations for flexible borrowing in structs
use crossbeam::channel::unbounded;
use std::thread;
fn main() {
let (tx, rx) = unbounded();
Crossbeam for advanced concurrent data structures
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
use std::sync::mpsc;
use std::thread;
fn main() {
let (tx, rx) = mpsc::channel();
Channels (mpsc) for message passing between threads
use clap::Parser;
#[derive(Parser, Debug)]
#[command(author, version, about)]
struct Args {
#[arg(short, long)]
clap for CLI argument parsing with derive macros
use my_crate::add;
#[test]
fn test_public_api() {
assert_eq!(add(3, 4), 7);
}
Integration tests in tests/ directory
Share this code
Here's the card — post it anywhere.