我有以下代码:
/// An error that encapsulates all possible configuration errors.
#[derive(Debug)]
pub enum Error {
/// An error that occured while parsing a yaml configuration.
Yaml(serde_yaml::Error),
}
impl From<serde_yaml::Error> for Error {
fn from(err: serde_yaml::Error) -> Error {
Error::Yaml(err)
}
}
/// A `Result` type alias for this config module's `Error` type.
pub type Result<T> = ::std::result::Result<T, Error>;
pub fn new(mut args: env::Args) -> Result<Config, Error> {
// initialize config_file variable
let config = serde_yaml::from_reader(config_file)?;
Ok(config)
}
serde_yaml::from_reader
返回serde_yaml::Result
,serde_yaml::Error
使用Result
的错误类型。上面的代码编译得很好。
那就是说,我应该打开Result
给我的serde_yaml::from_reader
来打电话Ok
然后立即重新打包成新的pub fn new(mut args: env::Args) -> Result<Config> {
// initialize config_file variable
serde_yaml::from_reader(config_file)
}
似乎有点好笑。换句话说,我真的很想能够写出:
error[E0308]: mismatched types
--> src/config.rs:28:9
|
18 | pub fn new(mut args: env::Args) -> Result<Config> {
| -------------- expected `std::result::Result<config::Config, config::Error>` because of return type
...
28 | serde_yaml::from_reader(config_file)
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ expected enum `config::Error`, found struct `serde_yaml::Error`
|
= note: expected type `std::result::Result<config::Config, config::Error>`
found type `std::result::Result<_, serde_yaml::Error>`
但是当我尝试这样做时,我得到以下编译器错误:
LoginController
这里发生了什么以及在这种情况下最常用的事情是什么?我应该保留我的代码吗?
答案 0 :(得分:4)
您有两种不同的错误类型。不同类型不兼容。除此之外别无其他。
值得注意的是,您并非只是&#34;重新包装&#34;价值;您将初始Result
值拉开,执行错误类型转换,如果 错误,则将函数分支出来,然后将值重新包装到不同的Result
类型。而且,你甚至不需要那里的变量;你可以把它写成Ok(serde_yaml::from_reader(config_file)?)
。
如果您真的不想使用?
和Ok
,则可以通过其他方式进行错误转换:
serde_yaml::from_reader(config_file)
.map_err(|e| e.into())
但这基本上是相同的,没有早期的错误回报&#34;一部分。