【问题标题】:How to handle "multiple applicable items in scope" error?如何处理“范围内的多个适用项目”错误?
【发布时间】:2020-12-20 11:20:01
【问题描述】:

我正在使用 fltk-rs 板条箱并遇到 “范围内的多个适用项目” 错误。

fltk = "0.10.14"
use fltk::{table::*};

pub struct AssetViewer {
    pub table: Table, 
}

impl AssetViewer {
    pub fn new(x: i32, y: i32, width: i32, height: i32) -> Self {
        let mut av = AssetViewer {
            table: Table::new(x,y,width-50,height,""),

        };
        av.table.set_rows(5);
        av.table.set_cols(5);
        av
    }
    pub fn load_file_images(&mut self, asset_paths: Vec<String>){
        self.table.clear(); //<- throws multiple applicable items in scope
    }
}

给出错误:

error[E0034]: multiple applicable items in scope
   --> src\main.rs:18:20
    |
18  |         self.table.clear(); //<- throws multiple applicable items in scope
    |                    ^^^^^ multiple `clear` found
    |
    = note: candidate #1 is defined in an impl of the trait `fltk::TableExt` for the type `fltk::table::Table`
    = note: candidate #2 is defined in an impl of the trait `fltk::GroupExt` for the type `fltk::table::Table`

我想指定我引用的是 TableExt 特征,而不是 GroupExt 特征。我该怎么做?

【问题讨论】:

  • 我认为完全限定名称应该可以工作。 fltk::GroupExt::clear(self.table)

标签: rust


【解决方案1】:

TLDR:使用完全限定的函数名:

fltk::GroupExt::clear(&mut self.table)

考虑这个简化的例子:

struct Bar;

trait Foo1 {
    fn foo(&self) {}
}
trait Foo2 {
    fn foo(&self) {}
}
impl Foo1 for Bar {}
impl Foo2 for Bar {}

fn main() {
    let a = Bar;
    a.foo()
}

编译失败,报错如下:

error[E0034]: multiple applicable items in scope
  --> src/main.rs:16:7
   |
16 |     a.foo()
   |       ^^^ multiple `foo` found
   |

编译器也会提出解决方案:

help: disambiguate the associated function for candidate #1
   |
16 |     Foo1::foo(&a)
   |

【讨论】:

    【解决方案2】:

    此实例中的编译器会推荐正确的修复程序。错误消息(自 1.48.0 起)包含以下帮助注释:

    help: disambiguate the associated function for candidate #1
        |
    18  |         fltk::TableExt::clear(&mut self.table);
        |         ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
    help: disambiguate the associated function for candidate #2
        |
    18  |         fltk::GroupExt::clear(&mut self.table);
        |         ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
    

    完整的错误信息实际上显示了 5 个候选项和 5 个帮助注释。


    顺便说一句,消除方法歧义的另一种语法是:

    <Table as fltk::TableExt>::clear(&mut self.table);
    

    尽管它比推荐的语法更冗长,并且仅在方法不采用 self 并因此无法推断出 Table 的情况下才需要。

    【讨论】:

      猜你喜欢
      • 2021-05-31
      • 1970-01-01
      • 2014-05-17
      • 1970-01-01
      • 2014-09-14
      • 2019-07-08
      • 1970-01-01
      • 1970-01-01
      • 2018-04-17
      相关资源
      最近更新 更多