Skip to content

Instantly share code, notes, and snippets.

@RandyMcMillan
Forked from rust-play/Playground.toml
Last active July 25, 2026 14:25
Show Gist options
  • Select an option

  • Save RandyMcMillan/795f5e2d8f8a8b2045536541e73518eb to your computer and use it in GitHub Desktop.

Select an option

Save RandyMcMillan/795f5e2d8f8a8b2045536541e73518eb to your computer and use it in GitHub Desktop.
Code shared from the Rust Playground
// ==========================================
// INCORRECT: Dyn-Incompatible Trait
// ==========================================
// Uncommenting this will cause a compilation error:
// "the trait `Processor` cannot be made into an object"
/*
trait Processor {
// Error 1: Uses `Self` in return position
fn duplicate(&self) -> Self;
// Error 2: Has a generic type parameter `T`
fn process_data<T>(&self, data: T);
}
*/
// ==========================================
// CORRECT: Dyn-Compatible Refactored Version
// ==========================================
use std::fmt::Debug;
trait Processor {
// 1. Valid dynamic dispatch method
fn name(&self) -> &str;
// 2. Exempted via `where Self: Sized` (cannot be called via `dyn Processor`)
fn _duplicate(&self) -> Self where Self: Sized;
// 3. Generic requirement removed or replaced with a trait object (type erasure)
fn process_data(&self, data: &dyn Debug);
}
struct AudioProcessor;
impl Processor for AudioProcessor {
fn name(&self) -> &str {
"AudioProcessor"
}
fn _duplicate(&self) -> Self {
AudioProcessor
}
fn process_data(&self, data: &dyn Debug) {
println!("Processing audio data: {:?}", data);
}
}
fn run_processor(p: &dyn Processor) {
println!("Running: {}", p.name());
p.process_data(&42); // Passes concrete data via trait object reference
// p._duplicate(); // ERROR: Cannot call because it requires `Self: Sized`
}
fn main() {
let audio = AudioProcessor;
run_processor(&audio);
}
@RandyMcMillan

Copy link
Copy Markdown
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment