Result types
Result types are returned by using Result<T, E> (or DiplomatResult<T, E>).
For example, let's say we wish to define a fallible constructor:
#![allow(unused)] fn main() { #[diplomat::bridge] mod ffi { #[diplomat::opaque] struct Thingy(u8); impl Thingy { pub fn try_create(string: &str) -> Result<Box<Thingy>, ()> { let parsed: Result<u8, ()> = string.parse().map_err(|_| ()); parsed.map(Thingy).map(Box::new) } } } }
On the C++ side, this will generate a method on Thingy with the signature
static diplomat::result<std::unique_ptr<Thingy>, std::monostate> try_create(const std::string_view string);
diplomat::result is a type that can be found in the generated diplomat_runtime.hpp file. The most basic APIs are .is_ok() and .is_err(), returning bools, and .ok() and .err() returning std::options. There are further APIs for constructing and manipulating these that can be found in the header file.
On backends that do not support Result, they will instead throw an error (i.e., Python/Nanobind and JS).