I'm still new to Rust. I want to throw an error message into Result<T, E>
and it seems to me you can't do that without match
. In Javascript you can basically call a callback(error, result)
anywhere in the function. What match
is doing ? and how to propagate an error with Result<T,E>
without match
?
I don't like using panic!
as it means the program will shuts off immediately when it encounters an error.
Thank you in advance.
use std::io::{Error, ErrorKind}; // im using std::io error here just for example fn check(array: Vec<usize>) -> Result<bool, Error> { let a = array.len(); // I need to make it error if the array.len() is 3 or above match a { 3 => Ok(true), _ => { let msg = format!("Invalid array size!"); Err(Error::new(ErrorKind::InvalidData, msg)) } } } fn main(){ let a = vec!(0, 2, 3, 5); let result = check(a); let kind = result.map_err(|e| e.kind()); println!("error kind: {:?}", kind); }
This doesn't works and prints expected "()", found enum "std::result::Result"
use std::io::{Error, ErrorKind}; fn check(array: Vec<usize>) -> Result<bool, Error> { // if array.len() is 3 or above it throws an error if array.len() >= 3 { let msg = format!("Invalid array size!"); Err(Error::new(ErrorKind::InvalidData, msg)) } Ok(true) } fn main(){ let a = vec!(0, 2, 3, 5); let result = check(a); let kind = result.map_err(|e| e.kind()); println!("error kind: {:?}", kind); }
PLAYGROUND: https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=bc9c7add4d5081a591413431738a79f5
https://stackoverflow.com/questions/66827800/how-to-throw-error-into-result-t-e-without-match-in-rust March 27, 2021 at 11:41AM
没有评论:
发表评论