Function to_dynamic
pub fn to_dynamic<T>(value: T) -> Result<Dynamic, Box<EvalAltResult>>where
T: Serialize,
Expand description
Serialize a Rust type that implements serde::Serialize
into a Dynamic
.
ยงExample
use rhai::{Dynamic, Array, Map};
use rhai::serde::to_dynamic;
use serde::Serialize;
#[derive(Debug, serde::Serialize, PartialEq)]
struct Point {
x: f64,
y: f64
}
#[derive(Debug, serde::Serialize, PartialEq)]
struct MyStruct {
a: i64,
b: Vec<String>,
c: bool,
d: Point
}
let x = MyStruct {
a: 42,
b: vec![ "hello".into(), "world".into() ],
c: true,
d: Point { x: 123.456, y: 999.0 }
};
// Convert the 'MyStruct' into a 'Dynamic'
let value = to_dynamic(x)?;
assert!(value.is::<Map>());
let map = value.cast::<Map>();
let point = map["d"].as_map_ref().unwrap();
assert_eq!(*point["x"].read_lock::<f64>().unwrap(), 123.456);
assert_eq!(*point["y"].read_lock::<f64>().unwrap(), 999.0);