Last active
April 19, 2023 17:04
-
-
Save fvilante/3f57f9ba412a07aeee82be212cd2d21c to your computer and use it in GitHub Desktop.
How to convert enum discriminant to trait objects
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
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); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
See also:
On-Stack Dynamic Dispatch
trait-object