为什么必须在对实现特征的类型的引用的集合中指定关联的类型? [英] Why must the associated type be specified in a collection of references to types implementing a trait?

查看:72
本文介绍了为什么必须在对实现特征的类型的引用的集合中指定关联的类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是一个令人反感的例子:

Here is an offending example:

// Some traits
trait Behaviour {
    type Sub: SubBehaviour;
}
trait SubBehaviour {}

// Some implementations of these traits
struct A;
impl Behaviour for A {
    type Sub = B;
}
struct B;
impl SubBehaviour for B {}

// Struct that holds a collection of these traits.
struct Example<'a> {
    behaviours: Vec<&'a Behaviour>,
}

impl<'a> Example<'a> {
    fn add_behaviour<T: Behaviour>(&mut self, b: &'a T) {
        self.behaviours.push(b);
    }
}

fn main() {
    let b = A;
    let mut e = Example {
        behaviours: Vec::new(),
    };
    e.add_behaviour(&b);
}

游乐场

我得到了:

error[E0191]: the value of the associated type `Sub` (from the trait `Behaviour`) must be specified
  --> src/main.rs:17:25
   |
17 |     behaviours: Vec<&'a Behaviour>,
   |                         ^^^^^^^^^ missing associated type `Sub` value

为什么必须指定此类型,特别是在我们仅存储对对象的引用的情况下?如何使此代码正常工作?

Why must this type must be specified, particularly in this case where we are only storing a reference to the object? How can I get this code to work?

推荐答案

您需要指定特征的关联类型(即Behavior<Sub = ???>).

You need to specify the associated type of the trait (i.e. Behavior<Sub = ???>).

在所有位置添加关联的类型时,它都会编译:

When adding the associated type at all places, it compiles:

struct Example<'a, S: SubBehaviour + 'a> {
    behaviours: Vec<&'a Behaviour<Sub = S>>,
}

impl<'a, S: SubBehaviour> Example<'a, S> {
    fn add_behaviour<T: Behaviour<Sub = S>>(&mut self, b: &'a T) {
        self.behaviours.push(b);
    }
}

在运行中查看在操场上在操场上

See this in action on the Playground

这篇关于为什么必须在对实现特征的类型的引用的集合中指定关联的类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆