首页 > 解决方案 > 我可以给完全限定的语法起别名吗?

问题描述

我有一些代码,其中有许多完全限定语法的实例;举个例子:

mod hal {
    pub trait Backend {
        type Device;
    }
}

mod back {
    pub struct Backend {}

    impl ::hal::Backend for Backend {
        type Device = i32;
    }
}

fn main() {
    let d: back::Backend::Device = 0;
}

操场

为了避免以下错误:

error[E0223]: ambiguous associated type
  --> src/main.rs:16:12
   |
16 |     let d: back::Backend::Device = 0;
   |            ^^^^^^^^^^^^^^^^^^^^^ ambiguous associated type
   |
   = note: specify the type using the syntax `<back::Backend as Trait>::Device`

有没有一种可以别名的好方法SomeType as SomeTrait?然后,只要需要这个完全限定语法的实例,我就可以写:

<S>::associated_fn(...)

请注意,不会发生此错误,因为某些 trait 的定义实际上有多个实现(根据Rust 编程语言,这是 FQS 应该处理的)。

标签: syntaxrusttype-alias

解决方案


在您的示例中,您可以重命名某些部分,以便可以在不冲突的情况下以缩写形式引用它们:

use hal::Backend;
use back::Backend as BackendImpl;

fn main() {
    let d: <BackendImpl as Backend>::Device = 0;
}

您还可以考虑定义一个类型别名,这样访问起来就不那么模棱两可了:

mod hal {
    pub trait Backend {
        type Device;
    }
}

mod back {
    pub struct Backend {}
    pub type Device = i32;
    impl ::hal::Backend for Backend {
        type Device = Device;
    }
}

fn main() {
    let d: back::Device = 0;
}

推荐阅读