Created
September 27, 2018 16:27
-
-
Save rust-play/4e0b973e1ebf857bd6dbb821350b1c68 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
use std::any::Any; | |
use std::any::TypeId; | |
#[derive(Debug)] | |
enum Scalar { | |
String(String), | |
Unsigned(u32), | |
Bool(bool), | |
} | |
impl Scalar { | |
pub fn set(&mut self, val: &Any) { | |
if let Some(val) = val.downcast_ref::<String>() { | |
if let Scalar::String(ref mut s) = self { | |
s.clear(); | |
s.push_str(val); | |
return; | |
} else { | |
panic!("Not a string scalar"); | |
} | |
} | |
if let Some(val) = val.downcast_ref::<u32>() { | |
if let Scalar::Unsigned(ref mut s) = self { | |
*s = *val; | |
return; | |
} else { | |
panic!("Not a unsigned scalar"); | |
} | |
} | |
// Rust defaults to i32 for unknown integer types | |
if let Some(val) = val.downcast_ref::<i32>() { | |
if let Scalar::Unsigned(ref mut s) = self { | |
*s = *val as u32; | |
return; | |
} else { | |
panic!("Not a unsigned scalar"); | |
} | |
} | |
if let Some(val) = val.downcast_ref::<bool>() { | |
if let Scalar::Bool(ref mut s) = self { | |
*s = *val; | |
return; | |
} else { | |
panic!("Not a boolean scalar"); | |
} | |
} | |
panic!("Unrecognized type"); | |
} | |
} | |
fn main() { | |
let mut s = Scalar::String(String::new()); | |
s.set(&"foobar".to_string()); | |
// s.set(&42u32); // panics at runtime | |
// s.set(&42); // panics at runtime for a different reason | |
let mut b = Scalar::Bool(false); | |
b.set(&true); | |
let mut u = Scalar::Unsigned(0); | |
u.set(&42); | |
let mut v = Vec::new(); | |
v.push(s); | |
v.push(b); | |
v.push(u); | |
println!("Scalars: {:?}", v); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment