2

I want a function to take in a reference to input and return a value if the input is valid or an error if its invalid. Here's my attempt but I get an error:

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);
}
error[E0423]: expected value, found struct `ParseIntError`
 --> src/main.rs:6:46
  |
6 |         _ => return Err(ParseIntError {kind: ParseIntError} )
  |                                              ^^^^^^^^^^^^^
  |
help: use struct literal syntax instead
  |
6 |         _ => return Err(ParseIntError {kind: ParseIntError { kind: val }} )
  |                                              ~~~~~~~~~~~~~~~~~~~~~~~~~~~

ParseIntError is just temporary for my testing. How can I return an error? How can I solve this?

kmdreko
  • 42,554
  • 6
  • 57
  • 106
curlywei
  • 682
  • 10
  • 18

1 Answers1

2

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.

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

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)
}
kmdreko
  • 42,554
  • 6
  • 57
  • 106
  • Oh! I got it. Regarding `struct LengthError;`. We only can use `struct`, instead of `enum` in rust, right! – curlywei Dec 04 '22 at 17:33
  • @curlywei Not sure how you came to understand *that* from my answer, an `enum` can be used as an error just fine. I just provided the simplest dummy type to use as an error. – kmdreko Dec 04 '22 at 17:35
  • OK! I solved my problem. `std::num::ParseFloatError` seems to adopt this solution. (similar to your answer) – curlywei Dec 04 '22 at 17:39