[][src]Function rhai::serde::to_dynamic

pub fn to_dynamic<T: Serialize>(value: T) -> Result<Dynamic, Box<EvalAltResult>>

Serialize a Rust type that implements serde::Serialize into a Dynamic.

Example

use rhai::{Dynamic, Array, Map, INT};
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"].read_lock::<Map>().unwrap();
assert_eq!(*point["x"].read_lock::<f64>().unwrap(), 123.456);
assert_eq!(*point["y"].read_lock::<f64>().unwrap(), 999.0);