Skip to content

How to return {:ok, result} from say NifResult<Type>? #659

Closed

Description

@jonmdev

To match the Elixir convention, I am trying to return from my Rustler functions {:ok, result} or {:error, error_string}.

I can do the :error case as follows, but can't solve the :ok case:

fn get_id(index: i64) -> NifResult<String> {
    if index >= 1) {
        return Err(rustler::Error::Term(Box::new("attempt to get index outside range"))); 
    }
    else {
        let hello = "HELLO".to_string();
        return Ok( hello); //HOW TO MAKE THIS RETURN {:ok, "HELLO"} rather than just "HELLO"?
    }
}

With the above code, I am able to get {:error, "attempt to get index outside range"} but I still cannot get {:ok, "HELLO"}.

If I just return Ok(hello); then I just get the result without the {:ok, result} tuple wrapping of it.

I also tried

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

with

        let result = (my_atoms::ok, hello); 
        return Ok(result); 

But this does not work either. I tried ChatGPT out of interest but it is just giving me hallucinations of things that don't exist (maybe did at one time but don't now).

It seems logical that if you are going to get {:error, reason} you should also want to get {:ok, result}

How can I do this? Is there some more correct way to do it I am not? Thanks for any help.

Activity

  1. locked and limited conversation to collaborators on Oct 16, 2024
  2. converted this issue into a discussion #660 on Oct 16, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions