Function from_dynamic
pub fn from_dynamic<'de, T>(
value: &'de Dynamic,
) -> Result<T, Box<EvalAltResult>>where
T: Deserialize<'de>,
Expand description
Deserialize a Dynamic
value into a Rust type that implements serde::Deserialize
.
ยงExample
use rhai::{Dynamic, Array, Map, INT};
use rhai::serde::from_dynamic;
use serde::Deserialize;
#[derive(Debug, Deserialize, PartialEq)]
struct Hello {
a: INT,
b: bool,
}
#[derive(Debug, Deserialize, PartialEq)]
struct Test {
int: u32,
seq: Vec<String>,
obj: Hello,
}
let mut map = Map::new();
map.insert("int".into(), Dynamic::from(42_u32));
let mut map2 = Map::new();
map2.insert("a".into(), (123 as INT).into());
map2.insert("b".into(), true.into());
map.insert("obj".into(), map2.into());
let arr: Array = vec!["foo".into(), "bar".into(), "baz".into()];
map.insert("seq".into(), arr.into());
let value: Test = from_dynamic(&map.into())?;
let expected = Test {
int: 42,
seq: vec!["foo".into(), "bar".into(), "baz".into()],
obj: Hello { a: 123, b: true },
};
assert_eq!(value, expected);