Skip to main content

RNativeType

Derive Macro RNativeType 

Source
#[derive(RNativeType)]
Expand description

Derive macro for implementing RNativeType on a newtype wrapper.

This allows newtype wrappers around R native types to work with Vec<T>, &[T] conversions and the Coerce<R> traits. The inner type must implement RNativeType.

§Supported Struct Forms

Both tuple structs and single-field named structs are supported:

use miniextendr_api::RNativeType;

// Tuple struct (most common)
#[derive(Clone, Copy, RNativeType)]
struct UserId(i32);

// Named single-field struct
#[derive(Clone, Copy, RNativeType)]
struct Temperature { celsius: f64 }

§Generated Code

For struct UserId(i32), this generates:

impl RNativeType for UserId {
    const SEXP_TYPE: SEXPTYPE = <i32 as RNativeType>::SEXP_TYPE;

    unsafe fn dataptr_mut(sexp: SEXP) -> *mut Self {
        <i32 as RNativeType>::dataptr_mut(sexp).cast()
    }
}

§Using the Newtype with Coerce

Once RNativeType is derived, you can implement Coerce to/from the newtype:

impl Coerce<UserId> for i32 {
    fn coerce(self) -> UserId { UserId(self) }
}

let id: UserId = 42.coerce();

§Requirements

  • Must be a newtype struct (exactly one field, tuple or named)
  • The inner type must implement RNativeType (i32, f64, RLogical, u8, Rcomplex)
  • Should also derive Copy (required by RNativeType: Copy)