syntax - 我可以给完全限定的语法起别名吗?
问题描述
我有一些代码,其中有许多完全限定语法的实例;举个例子:
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 应该处理的)。
解决方案
在您的示例中,您可以重命名某些部分,以便可以在不冲突的情况下以缩写形式引用它们:
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;
}
推荐阅读
- flutter - 有没有办法获取呈现的 ListView Widget 的当前键?
- xslt - XSLT 3.0 在应用模板中使用变量进行动态选择?
- r - 设置工作目录:“C:/Documents and Settings/...”下的“setwd 中的错误:无法更改工作目录”
- node.js - 未通过 Azure 服务总线队列接收消息
- angular - 如何将参数从 Nativescript 中的兄弟路由传递给子路由
- spring - Gatling 不适用于 SpringBoot 2.0.1.RELEASE
- php - SMTP 错误:无法连接到服务器:(0)并且邮件发送成功但没有收到电子邮件
- spring-boot - Spring Boot elasticsearch产生警告:找不到id的传输响应处理程序
- npm - 使用不正确的 index.js 源路径为 React 应用程序运行构建
- java - Kafka:并行有界批处理