小编Jea*_*ean的帖子

如何将特征与使用特征相关类型作为参数的超级特征绑定?

我有一个Trait关联类型的特征Trait::Associated.我试图通过要求它可以通过其关联类型进行索引来约束该特征,如下所示:

use std::ops::Index;

pub trait Trait: Index<Trait::Associated> {
    type Associated;
}
Run Code Online (Sandbox Code Playgroud)

但是,编译器抱怨相关类型不明确

error[E0223]: ambiguous associated type
 --> src/main.rs:3:24
  |
3 | pub trait Trait: Index<Trait::Associated> {
  |                        ^^^^^^^^^^^^^^^^^ ambiguous associated type
  |
  = note: specify the type using the syntax `<Type as Trait>::Associated`
Run Code Online (Sandbox Code Playgroud)

我也尝试将相关类型称为Self::Associated,但随后编译器抗议类型和特征之间的循环引用:

error[E0391]: cyclic dependency detected
 --> src/main.rs:3:1
  |
3 | pub trait Trait: Index<Self::Associated> {
  | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ cyclic reference
  |
note: the cycle begins when computing the supertraits of `Trait`...
 --> …
Run Code Online (Sandbox Code Playgroud)

rust

10
推荐指数
1
解决办法
1333
查看次数

标签 统计

rust ×1