Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Rust Vec: How to return error with Result<T,E>?

I have a function with reference input, and return:

  • return value: if input is valid
  • return error: if input is invalid
fn get_fourth(input: &Vec<i32>) -> Result<i32, ParseIntError> {
    let q = match input.get(4) {
        Some(v) => v,
        _ => return Err(ParseIntError {kind: ParseIntError} )
    };
    Ok(*q)
}

ParseIntError is just temporary for my testing return error.

I got error

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

   Compiling playground v0.0.1 (/playground)
error[E0423]: expected value, found struct `ParseIntError`
6 |         _ => return Err(ParseIntError {kind: ParseIntError} )
  |                                              ^^^^^^^^^^^^^
  |
help: use struct literal syntax instead
  |
6 |         _ => return Err(ParseIntError {kind: ParseIntError { kind: val }} )

How do I solved it?

Full code

use std::num::ParseIntError;

fn get_fourth(input: &Vec<i32>) -> Result<i32, ParseIntError> {
    let q = match input.get(4) {
        Some(v) => v,
        _ => return Err(ParseIntError {kind: ParseIntError} )
    };
    Ok(*q)
}

fn main() {
    let my_vec = vec![9, 0, 10];
    let fourth = get_fourth(&my_vec);
}

>Solution :

You’re returning an error just fine, its your use of ParseIntError that is messed up. You cannot construct an instance of ParseIntError yourself because its fields are private and there’s no public constructing function.

ParseIntError is just temporary for my testing return error.

Well go ahead and make your own non-temporary error and you’ll see the rest of your code works just fine:

struct LengthError;

fn get_fourth(input: &Vec<i32>) -> Result<i32, LengthError> {
    let q = match input.get(4) {
        Some(v) => v,
        _ => return Err(LengthError)
    };
    Ok(*q)
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading