Having trouble with Rustler returning :ok (Erlang error: :invalid_struct:)

I’m having some trouble just returning ok from rust. The following fails with an Erlang error: :invalid_struct:

mod atoms {
    rustler::atoms! {
        ok
    }
}

#[rustler::nif]
pub fn backend_deallocate(array: ExAf) -> Atom {
    let exaf_array = array.resource.value();

    match exaf_array {
        ExAfArray::U8(a) => drop(a),
        ExAfArray::U16(a) => drop(a),
        ExAfArray::U32(a) => drop(a),
        ExAfArray::U64(a) => drop(a),
        ExAfArray::S16(a) => drop(a),
        ExAfArray::S32(a) => drop(a),
        ExAfArray::S64(a) => drop(a),
        ExAfArray::F16(a) => drop(a),
        ExAfArray::F32(a) => drop(a),
        ExAfArray::F64(a) => drop(a),
        ExAfArray::C64(a) => drop(a),
        ExAfArray::C128(a) => drop(a),
    }

    atoms::ok()
}

How can I return :ok (or any other atom) from Rust?

1 Like

I don’t really understand what I’m doing with Rustler, but this recipe seems to work (for me):

#[rustler::nif]
pub fn backend_deallocate(array: ExAf) -> Result<Atom> {
   ...

    return Ok(atoms::ok());
}
2 Likes

Thanks for your reply @mindok!

It turns out the reason I was getting an Erlang Error: :invalid_struct error was because I was passing in an “invalid struct” (i.e. an incorrect input for my NIF) and not because of any issues with the rustler output.

Here’s what (in essence) worked for me:

#[rustler::nif]
pub fn ok() -> Atom {
    atoms::ok()
}
4 Likes

You can use rustler::types::atom module to use predefined atoms: nil, ok, error, true, and so on.