Skip to content

Instantly share code, notes, and snippets.

@badboy
Forked from rust-play/playground.rs
Created September 27, 2018 16:27
Show Gist options
  • Save badboy/72345e1f8989de250b4ad97838f58518 to your computer and use it in GitHub Desktop.
Save badboy/72345e1f8989de250b4ad97838f58518 to your computer and use it in GitHub Desktop.
Code shared from the Rust Playground
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