Rust 方法通用和特定

问题描述 投票:0回答:1

我想我正在尝试在这里做一件完全正常的事情,即拥有一个具有默认方法实现的泛型类型,以及一个具有更具体方法实现的特定类型。代码看起来非常简单:

struct V<L> { value: L, }

impl<L> V<L> {
    fn m(&self) { println!("generic"); }
}
struct MyClass;

impl V<MyClass> {
    fn m(&self) { println!("specific"); }
}

pub fn main() {
    let v1 = V { value: MyClass };
    v1.m();
}

这给了我一个重复的方法错误——在两个

impl
块中定义相同的方法名称会得到相同的错误。但是 Rust 不是应该能够找到特定的而不是通用的吗?

error[E0592]: duplicate definitions with name `m`
 --> src/main.rs:3:5
  |
3 |     fn m(&self) { println!("generic"); }
  |     ^^^^^^^^^^^ duplicate definitions for `m`
...
8 |     fn m(&self) { println!("specific"); }
  |     ----------- other definition for `m`

error[E0034]: multiple applicable items in scope
  --> src/main.rs:12:8
   |
12 |     v1.m();
   |        ^ multiple `m` found
   |
note: candidate #1 is defined in an impl for the type `V<L>`
  --> src/main.rs:3:5
   |
3  |     fn m(&self) { println!("generic"); }
   |     ^^^^^^^^^^^
note: candidate #2 is defined in an impl for the type `V<MyClass>`
  --> src/main.rs:8:5
   |
8  |     fn m(&self) { println!("specific"); }
   |     ^^^^^^^^^^^
generics rust
1个回答
0
投票

如果我理解正确的话,你想要在这里专业化。目前正在开发中,正在跟踪问题此处。在这里,您尝试覆盖通用实现,而不是针对具体类型的默认实现。默认实现可以被覆盖,但通用不能。

© www.soinside.com 2019 - 2024. All rights reserved.