Skip to content

Instantly share code, notes, and snippets.

@0xa
Created June 10, 2019 21:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save 0xa/5d591a95203d1f2afd723dc7a68dfad0 to your computer and use it in GitHub Desktop.
Save 0xa/5d591a95203d1f2afd723dc7a68dfad0 to your computer and use it in GitHub Desktop.
#[derive(Debug, PartialEq, Eq, Clone)]
struct Custo {
pub d: i32,
}
/// A Struct with FieldVTable
/// a StruTypes enum will be generated too
#[derive(Debug, FieldVTableDerive)]
struct Stru {
pub one: String,
pub two: usize,
pub three: Custo,
}
fn main() {
let s = Stru { one: "test".to_owned(), two: 1312, three: Custo { d: 1 } };
// It works as a trait object too
let mut s: Box<dyn FieldVTable<StruTypes>> = Box::new(s);
// Get field by name (as fast as a big match)
if let Ok(StruTypes::two(n)) = s.get_field("two") {
assert_eq!(n, 1312);
}
// Set field by name (again a big match)
s.set_field("two", StruTypes::two(420)).unwrap();
assert_eq!(s.get_field("two").unwrap(), StruTypes::two(420));
// the generated enum wraps around the type of any field in the struct.
// it is checked at runtime but doesn't render the type system useless.
s.set_field("one", StruTypes::one("woah".into())).unwrap();
s.set_field("three", StruTypes::three(Custo { d: 2 })).unwrap();
assert!(s.set_field("four?", StruTypes::two(69)).is_err());
assert!(s.set_field("one", StruTypes::two(69)).is_err());
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment