我试图将多种不同的错误类型合并为单一的复合错误类型。我很难理解为什么隐式类型转换没有发生在我的例子中:
use std::io::Error;
struct ParseError;
enum CompositeError {
IoError(std::io::Error),
ParseError(ParseError)
}
impl From<std::io::Error> for CompositeError {
fn from(error: std::io::Error) -> Self {
CompositeError::IoError(error)
}
}
impl From<ParseError> for CompositeError {
fn from(error: ParseError) -> Self {
CompositeError::ParseError(error)
}
}
fn open_file(path: &str) -> Result<std::fs::File, std::io::Error> {
std::fs::File::open(path)
}
fn parse_file(file: std::fs::File) -> Result<bool, ParseError> {
Err(ParseError)
}
fn open_file_and_parse(path: &str) -> Result<bool, CompositeError> {
open_file(path).and_then(|f| parse_file(f))
}
fn main() {
match open_file_and_parse("C:\rust-sandbox\src\main.rs") {
Ok(_) => {}
Err(e) => {
match e {
CompositeError::IoError(_) => {}
CompositeError::CustomError(_) => {}
}
}
}
}
错误是:
error[E0308]: mismatched types
--> srcmain.rs:32:23
|
32 | .and_then(|f| parse_file(f))
| ^^^^^^^^^^^^^
| |
| expected struct `std::io::Error`, found struct `ParseError`
| help: try using a variant of the expected enum: `Ok(parse_file(f))`
|
= note: expected enum `Result<_, std::io::Error>`
found enum `Result<bool, ParseError>`
我期望open_file(path).and_then(|f| parse_file(f))
行会自动检测它应该返回CompositeError
,并使用From
trait实现进行类型转换,但显然我是错误的。
我在这里做错了什么?
因为open_file返回Result<std::fs::File,>但预期是Result<bool,>
fn open_file_and_parse(path: &str) -> Result<bool, CompositeError> {
let _ = open_file(path).and_then(|f| parse_file(f))?;
Ok(true)
}