rune::runtime

Derive Macro FromValue

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

Derive macro for the FromValue trait for converting types from the dynamic Value container.

This can be implemented for structs and variants.

For structs, this will try to decode any struct-like data into the desired data type:

use std::sync::Arc;
use rune::{FromValue, Vm};

#[derive(Debug, PartialEq, FromValue)]
struct Foo {
    a: u64,
    b: u64,
}

let mut sources = rune::sources! {
    entry => {
        struct Foo {
            a,
            b,
        }

        pub fn main() {
            Foo { a: 1, b: 2 }
        }
    }
};

let unit = rune::prepare(&mut sources).build()?;

let mut vm = Vm::without_runtime(Arc::new(unit));
let foo = vm.call(["main"], ())?;
let foo: Foo = rune::from_value(foo)?;

assert_eq!(foo, Foo { a: 1, b: 2 });

For enums, the variant name of the rune-local variant is matched:

use std::sync::Arc;
use rune::{FromValue, Vm};

#[derive(Debug, PartialEq, FromValue)]
enum Enum {
    Variant(u32),
    Variant2 { a: u32, b: u32 },
}

let mut sources = rune::sources! {
    entry => {
        enum Enum {
            Variant(a),
        }

        pub fn main() {
            Enum::Variant(42)
        }
    }
};

let unit = rune::prepare(&mut sources).build()?;

let mut vm = Vm::without_runtime(Arc::new(unit));
let foo = vm.call(["main"], ())?;
let foo: Enum = rune::from_value(foo)?;

assert_eq!(foo, Enum::Variant(42));