extendr_macros

Derive Macro TryFromRobj

Source
#[derive(TryFromRobj)]
Expand description

Derives an implementation of TryFrom<Robj> for Struct and TryFrom<&Robj> for Struct on this struct.

This allows any R object supporting the $ operator (generally a list or an environment) to be converted into that struct, as long as the corresponding fields on the R object are of a compatible type to those on the Rust struct.

§Examples

In the below example, foo_from_list is an instance of the Foo struct, that has been converted from an R list:

use extendr_api::prelude::*;
use extendr_macros::TryFromRobj;

#[derive(TryFromRobj, PartialEq, Debug)]
struct Foo {
    a: u64,
    b: String
}
let native_foo = Foo { a: 5, b: "bar".into() };
let foo_from_list: Foo = R!("list(a = 5, b = 'bar')")?.try_into()?;
assert_eq!(native_foo, foo_from_list);

See IntoRobj for converting arbitrary Rust types into R type by using R’s list / List.