如何处理"作用域中存在多个适用项"错误?

4

我正在使用 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) - Ivan C
2个回答

5

简化版:使用完全限定的函数名称:

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)
   |

1
在此情况下,编译器建议正确的修复方法。错误消息(截至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时才需要使用它。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接