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
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.
ParseIntErroris 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)
}