我有这段代码:
fn do_stuff() -> Result<i32, String> {
let repo = git2::Repository::open(".")?;
// ...
}
这不起作用,因为git2::Repository::open()
的错误类型不是String
。(是的,我在错误处理方面有些懒惰,使用字符串。这是一个很小的程序,请勿起诉我。)
error[E0277]: the trait bound `std::string::String: std::convert::From<git2::Error>` is not satisfied
--> src/main.rs:94:13
|
94 | let repo = Repository::open(".")?;
| ^^^^^^^^^^^^^^^^^^^^^^ the trait `std::convert::From<git2::Error>` is not implemented for `std::string::String`
|
= help: the following implementations were found:
= help: <std::string::String as std::convert::From<&'a str>>
= help: <std::string::String as std::convert::From<std::borrow::Cow<'a, str>>>
= note: required by `std::convert::From::from`
我尝试加入了这个:
impl std::convert::From<git2::Error> for String {
fn from(err: git2::Error) -> Self {
err.to_string()
}
}
但这是不允许的,因为它没有引用此 crate 中定义的任何类型。
我知道我可能可以使用 .map_err()
,但我真的希望它可以自动发生。我有点觉得我以前也做过这个工作,这有点烦人!