Skip to main content

IntoJs

Derive Macro IntoJs 

Source
#[derive(IntoJs)]
{
    // Attributes available to this derive:
    #[qjs]
}
Expand description

A macro for deriving IntoJs for plain-data structs.

Generated impls construct a JavaScript object (for named-field structs), a JavaScript array (for tuple structs), or undefined (for unit structs) and write each field in turn via Object::set or Array::set.

The supported #[qjs(...)] attributes are the same as for FromJs; see its documentation for details.

§Example

use rquickjs::{CatchResultExt, Context, IntoJs, Runtime};

#[derive(IntoJs)]
struct Pair(u32, String);

let rt = Runtime::new().unwrap();
let ctx = Context::full(&rt).unwrap();
ctx.with(|ctx| {
    ctx.globals().set("pair", Pair(3, "gamma".into())).unwrap();
    ctx.eval::<(), _>(
        r#"if (pair[0] !== 3 || pair[1] !== "gamma") { throw new Error() }"#,
    )
    .catch(&ctx)
    .unwrap();
});

§Incompatibility with class

This derive cannot be stacked on a type that is also tagged with #[rquickjs::class]. #[class] already generates an IntoJs impl that round-trips through a Class<Self> instance, whereas this derive writes the value as a plain JS object. The two representations are mutually exclusive; combining them produces a compile error pointing at the offending derive.