Introduction

Call Rust code in R!

This is the website for extendr, a developer-first utility for building R packages that call Rust code. Of course, you do not have to be a package developer to find some use in extendr. In fact, anyone who has a need to call Rust in R can do so with ease. Consider this basic example:

# create a Rust function
rextendr::rust_function(
  "fn add(a:f64, b:f64) -> f64 { a + b }",
  quiet = TRUE
)

# call it from R
add(2.5, 4.7)
[1] 7.2

Moving beyond these simple, one-off cases, however, is where extendr really shines. Any time you have lots of really complex Rust code that requires seamless integration with R, notably within a package, extendr is the tool for you.

Now largely owing to the fact that we are bridging programming languages, you will rarely proceed directly to extendr’s Rust API. You will instead reach for the R package rextendr, which works sort of like usethis, automating many of the repetitive tasks required to setup or scaffold your project, so you can focus on the important business of writing code. This is done by calling rextendr::use_extendr(), which should feel familiar to anyone who has worked with usethis::use_cpp11().

Create an R package

The process of building a Rust-powered R package with extendr boils down to three simple steps:

  1. Setup R package with usethis::create_package().
  2. Add extendr scaffolding with rextendr::use_extendr().
  3. Build and document with devtools::document().

Once you have worked through those steps, you can then load your package with devtools::load_all() and start using your package! Here is an example with just the defaults:

# setup R package
usethis::create_package("helloextendr")

# add extendr scaffolding
rextendr::use_extendr()

# build and document package
devtools::document()

# load package
devtools::load_all()

# call rust function
hello_world()
[1] "Hello world!"

A Rust-powered R package in one fell swoop! Now, if you want to see a complete example of an actual R package, check out the heck example.

What’s next?