【问题标题】:Is it good practice to require associated Error types implement Debug trait?要求关联的错误类型实现调试特征是一种好习惯吗?
【发布时间】:2019-04-30 23:03:29
【问题描述】:

我遇到了piston2d-graphics crate 的问题。当我尝试对从graphics::character::CharacterCache::character 方法获得的Result 使用expect() 方法时,结果证明我不能——因为它需要Result 的Error 类型来实现std::fmt::Debug trait:

error[E0599]: no method named `expect` found for type `std::result::Result<graphics::character::Character<'_, <G as graphics::Graphics>::Texture>, <C as graphics::character::CharacterCache>::Error>` in the current scope
  --> src/some_file.rs:44:53
   |
44 |             let ch_glyph = glyphs.character(34, ch).expect("Couldn't load character");
   |                                                     ^^^^^^
   |
   = note: the method `expect` exists but the following trait bounds were not satisfied:
           `<C as graphics::character::CharacterCache>::Error : std::fmt::Debug`

Error 这是CharacterCache trait 中的关联(嵌套)类型。我可以轻松地提交添加要求的 PR,然后使用简单的派生宏将其实现添加到所有其他 crate。这似乎是合理的,因为expect()和其他相关方法在Rust中一直使用,但我不确定。是 Rust 的方式,还是有理由不这样做?


我用它发生的例子来描述这个问题,但它与活塞无关,我的问题是关于 Rust 中的一般模式。所以标签rust-piston是无关的,请不要添加到问题中。

【问题讨论】:

  • 在调用 expect 的函数(以及可能调用第一个函数的其他函数)上添加 where &lt;C as graphics::character::CharacterCache&gt;::Error : std::fmt::Debug 也应该可以解决问题。
  • @FrancisGagné 但是除非我真正修复我正在使用的库,否则此功能将无法使用,而这个问题正是关于我是否应该这样做
  • 哦,我假设有问题的错误类型已经实现Debug。那没关系!

标签: rust


【解决方案1】:

要求关联的错误类型实现 Debug trait 是一种好习惯吗?

是的,如果可能的话。也许他们忘记了。

解决这个问题的一种方法是使用map_err(),这里是问题的MCVE:

struct Error;

fn foo() -> Result<(), Error> {
    Ok(())
}

fn main() {
    foo().expect("no error");
}
error[E0599]: no method named `expect` found for type `std::result::Result<(), Error>` in the current scope
 --> src/main.rs:8:11
  |
8 |     foo().expect("no error");
  |           ^^^^^^
  |
  = note: the method `expect` exists but the following trait bounds were not satisfied:
          `Error : std::fmt::Debug`

使用map_err()产生一个实现Debug的错误,这可能是你自己的自定义错误,在下面的例子中,我只是将()作为错误返回:

struct Error;

fn foo() -> Result<(), Error> {
    Ok(())
}

fn main() {
    foo().map_err(|_| ()).expect("no error");
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-03-02
    • 2016-04-01
    • 2020-03-31
    • 2018-07-29
    • 2013-03-30
    • 1970-01-01
    • 2023-03-30
    相关资源
    最近更新 更多