I am working on a parser and I keep getting an error on this part of my code.
impl FromStr for Binop {
type Err = ParseError;
fn from_str(s: &str) -> Result<Self, Self::Err> {
Ok(match s {
" " => Binop::Add,
"*" => Binop::Mul,
"-" => Binop::Sub,
"/" => Binop::Div,
"<" => Binop::Lt,
"==" => Binop::Eq,
_ => {return Err(ParseError); } // <---- Error Here
})
}
}
I've tried writing an actual string inside the parenthesis and a bunch of other stuff & I just can't seem to understand what the error means.
Full error:
error[E0308]: mismatched types
--> grumpy/src/isa.rs:212:32
|
212 | _ => {return Err(ParseError); }
| ^^^^^^^^^^ expected struct `ParseError`, found fn item
|
::: grumpy/src/lib.rs:17:1
|
17 | pub struct ParseError(String);
| ------------------------------ fn(String) -> ParseError {ParseError} defined here
|
= note: expected struct `ParseError`
found fn item `fn(String) -> ParseError {ParseError}`
help: use parentheses to instantiate this tuple struct
|
212 | _ => {return Err(ParseError(_)); }
|
And I defined the ParseError as pub struct ParseError(String);
CodePudding user response:
The named tuple requires a String
value to be constructed. Note that a string literal has type &str
; you need to invoke the to_string()
method to turn it into a string:
Err(ParseError("foo".to_string()))
The compile error refers to fn item
because by itself, in this context, ParseError
refers to the implicit constructor function, which takes a String
and returns a ParseError
.