【问题标题】:How to use two traits with enum_dispatch?如何使用 enum_dispatch 的两个特征?
【发布时间】:2021-05-15 11:05:30
【问题描述】:

我试过了:

#[enum_dispatch(BarTrait, BazTrait)]
pub enum Foo {
    VariantZero,
    ...
}

它似乎忽略了第一个之后的任何特征,默默地。

这会导致错误,因为在这种情况下编译器似乎不相信 Foo 实现了 BazTrait。


更新:只要BazTraitFoo 在同一个板条箱中,@kmdreko 的code 就可以正常工作。

BazTrait 位于另一个 crate 中时,该 crate 也使用 enum_dispatchBazTrait 被忽略并导致以下形式的两个错误:

error[E0599]: no method named `baz` found for enum `Foo` in the current scope
  --> src/main.rs:53:9
   |
45 | enum Foo {
   | -------- method `baz` not found for this
...
53 |     foo.baz();
   |         ^^^ method not found in `Foo`
   |
   = help: items from traits can only be used if the trait is implemented and in scope
   = note: the following trait defines an item `baz`, perhaps you need to implement it:
           candidate #1: `mylib::BazTrait`

请务必注意,#[enum_dispatch(BarTrait, BazTrait)]pub enum Foo { 都没有错误。

【问题讨论】:

  • 你能举一个更完整的例子吗? This code 似乎工作得很好。
  • 感谢您的示例。我将在早上发布一个更完整的示例。我不知道enum_dispatch 是否甚至可以处理多个特征,所以感谢您的确认。
  • 我可以确认您的代码在同一个板条箱中运行良好。我用新的观察更新了这个问题。

标签: rust enums dispatch enum-dispatch


【解决方案1】:

#[enum_dispatch] 属性不适用于 crate:

不幸的是,Rust 中的过程宏在某些方面受到限制,这将使您试图实现的目标变得不可能 - 特别是,它们是独立运行的 per-crate,因此无法获取信息从一个 crate 影响另一个 crate 的实现。

来自 enum_dispatch 的作者unrelated issue

【讨论】:

    猜你喜欢
    • 2018-02-25
    • 2020-05-17
    • 2020-05-30
    • 1970-01-01
    • 2019-09-14
    • 2012-09-02
    • 1970-01-01
    • 1970-01-01
    • 2017-10-25
    相关资源
    最近更新 更多