Skip to content

Instantly share code, notes, and snippets.

@fvilante
Last active April 19, 2023 17:04
Show Gist options
  • Save fvilante/3f57f9ba412a07aeee82be212cd2d21c to your computer and use it in GitHub Desktop.
Save fvilante/3f57f9ba412a07aeee82be212cd2d21c to your computer and use it in GitHub Desktop.
How to convert enum discriminant to trait objects
use std::fmt::Display;
enum Storage {
Number(u32),
Text(String),
}
struct Data {
storage: Storage
}
impl Data {
fn new() -> Self {
Self {
storage: Storage::Number(0)
}
}
fn get_display(&mut self, a: bool) -> &dyn Display {
if a==true {
self.storage = Storage::Number(42_u32);
if let Storage::Number(ref number) = &mut self.storage {
number
} else {
unreachable!()
}
} else {
self.storage = Storage::Text(String::from("This is a string"));
if let Storage::Text(ref text) = &mut self.storage {
text
} else {
unreachable!()
}
}
}
}
fn print(some_value: &dyn Display) {
println!("{}", some_value )
}
fn main() {
let mut data: Data = Data::new();
let response: &dyn Display = data.get_display(false);
print(response);
}
@fvilante
Copy link
Author

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