-
-
Save RandyMcMillan/795f5e2d8f8a8b2045536541e73518eb to your computer and use it in GitHub Desktop.
Code shared from the Rust Playground
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // ========================================== | |
| // 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); | |
| } |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
https://play.rust-lang.org/?version=stable&mode=debug&edition=2024&gist=b83ca21347327431ad0bf4648c3822e8