I am trying to convert a &str
to an enum
, but got the error Expected type Method found enum Result<_, MethodError>
at this line Err(e) => Err(e)
. How to properly return an error in this case?
use std::str::FromStr;
fn main() {
#[derive(Debug)]
pub enum Method {
GET,
DELETE,
POST,
PUT,
HEAD,
CONNECT,
OPTIONS,
TRACE,
PATCH,
}
impl FromStr for Method {
type Err = MethodError;
fn from_str(s: &str) -> Result<Self, Self::Err> {
match s {
"GET" => Ok(Self::GET),
"DELETE" => Ok(Self::DELETE),
"POST" => Ok(Self::POST),
"PUT" => Ok(Self::PUT),
"HEAD" => Ok(Self::HEAD),
"CONNECT" => Ok(Self::CONNECT),
"OPTIONS" => Ok(Self::OPTIONS),
"TRACE" => Ok(Self::TRACE),
"PATCH" => Ok(Self::PATCH),
_ => Err(MethodError),
}
}
}
pub struct MethodError;
let method:&str = "GET";
let methodE = match method.parse::<Method>() {
Ok(method) => method,
Err(e) => Err(e),
};
}
Thanks to everyone's comments, I've figured it out:
main
needs to return Result<(), MethodError>
return
keyword is necessary in match arm Err(e) => return Err(e)
use std::str::FromStr;
#[derive(Debug)]
pub enum Method {
GET,
DELETE,
POST,
PUT,
HEAD,
CONNECT,
OPTIONS,
TRACE,
PATCH,
}
impl FromStr for Method {
type Err = MethodError;
fn from_str(s: &str) -> Result<Self, Self::Err> {
match s {
"GET" => Ok(Self::GET),
"DELETE" => Ok(Self::DELETE),
"POST" => Ok(Self::POST),
"PUT" => Ok(Self::PUT),
"HEAD" => Ok(Self::HEAD),
"CONNECT" => Ok(Self::CONNECT),
"OPTIONS" => Ok(Self::OPTIONS),
"TRACE" => Ok(Self::TRACE),
"PATCH" => Ok(Self::PATCH),
_ => Err(MethodError),
}
}
}
#[derive(Debug)]
pub struct MethodError;
fn main() -> Result<(), MethodError> {
let method:&str = "GET";
let methodE = match method.parse::<Method>() {
Ok(method) => method,
Err(e) => return Err(e),
};
// this works too: let methodE: Method = method.parse()?;
Ok(())
}