gpt4 book ai didi

syntax - 我可以为完全限定的语法起别名吗?

转载 作者:行者123 更新时间:2023-11-29 08:00:15 24 4
gpt4 key购买 nike

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

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;
}

playground

为了避免这样的错误:

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

请注意,不会发生此错误,因为某些特征的定义实际上有多个实现(根据 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;
}

关于syntax - 我可以为完全限定的语法起别名吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52656814/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com