Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get a value from a Result?

Tags:

rust

How can I get the value of a struct which is returned in a Result from another function? Example below.

#[derive(Debug)]
pub struct Keypair(ed25519_dalek::Keypair);

pub fn keypair_from_seed(seed: &[u8]) -> Result<Keypair, Box<dyn error::Error>> {
    let dalek_keypair = ed25519_dalek::Keypair { secret, public };
    Ok(Keypair(dalek_keypair))
}
fn main(){
  //here seed_bytes is mnemonics
  let sk = keypair_from_seed(&seed_bytes);
  //sk contains the secret key and public key, i want to extract it different secret key & public key
}
like image 408
Nagaraj M Avatar asked Sep 12 '20 11:09

Nagaraj M


People also ask

How do I return a value from the result property?

This example shows how to use the System.Threading.Tasks.Task<TResult> type to return a value from the Result property. It requires that the C:\Users\Public\Pictures\Sample Pictures\ directory exists, and that it contains files.

How to return a value from a JavaScript function?

How to return a value from a JavaScript function? To return a value from a JavaScript function, use the return statement in JavaScript. You need to run the following code to learn how to return a value −

How do I return a result from a task?

Using this Task<T> class we can return data or value from a task. In Task<T>, T represents the data type that you want to returns as a result of the task. In the following example, the CalculateSum method takes an input integer value and calculates the sum of the number starting from 1 to that number.

What is the return value of calculatesum method in Java?

Here the CalculateSum method returns a double value. As the return value from the CalculateSum method is of double type, so here we need to use Task<double> as shown in the below example.


Video Answer


2 Answers

If you feel very confident

let sk = keypair_from_seed(&seed_bytes).unwrap();

or

let sk = keypair_from_seed(&seed_bytes).expect("my own failure message");

However, it is recommended to proceed like this

if let Ok(sk) = keypair_from_seed(&seed_bytes) {
    // ... use sk ...
} else {
    // ... sk is not available, may be should
    // we warn the user, ask for an alternative ... 
}

or, if you want to explicitly handle the error

match keypair_from_seed(&seed_bytes) {
    Ok(sk) => { 
        // ... use sk ...
    },
    Err(e) => {
        // ... sk is not available, and e explains why ...
    },
}

Note that, if the function containing these lines is also able to return an error, you can just propagate it with the ? notation (if the error returned by keypair_from_seed() is convertible into the error returned by your function)

let sk = keypair_from_seed(&seed_bytes)?;

see unwrap, expect, if let, match, ?

like image 77
prog-fh Avatar answered Oct 20 '22 10:10

prog-fh


Lets look the definition of Result in Rust documentation

enum Result<T, E> {
   Ok(T),
   Err(E),
}

So a Result is either Ok which contains a value with type T, or Err which contains a value with type E.

You have couple options to extract the value.

1- result.unwrap() or result.expect("error message")

This function returns the Ok value if result is Ok or panics the program (program is terminated). If you are sure that it doesn't contain error or you just want to write the correct case first and deal with error handling later it makes sense but you shouldn't use it all the time since it directly crashes the app when the value is not Ok. You can use it like this

let val = result.unwrap();
// or
let val = result.expect("oops not Ok");

Only difference of expect you can provide the error message yourself instead of the standard error message of unwrap.

2- Pattern matching

In Rust, pattern matching is used for enum types so that user can do the necessary thing based on the current variant of the enum. You can use it like this

match result {
    Ok(val) => {
        // Use val here....
    },
    Err(err) => {
        // Do something with the error if you want
    }
}

If you are going to handle only one variant, you can also use if let statement like this

if let Some(val) = result {
    // Do something with val
}
like image 20
f.smith Avatar answered Oct 20 '22 09:10

f.smith