创建一个特征,该特征是借用价值之上其他特征的组成

时间:2018-07-10 23:19:50

标签: rust

我正在尝试创建一个将其他特征融合在一起的特征,但要在这些值的借用版本上输入其特征,而不是对其进行所有权。在此示例中,我将其减少为一个。

例如:

use std::ops::Add;

trait Foo
where
    for<'a> &'a Self: Add<Output = Self>,
{
}

似乎应该在需要定义Foo的地方创建特征Add。但是,当我尝试使用它时,这似乎不起作用。

#[derive(Debug)]
struct Two<T> {
    x: T,
    y: T,
}

impl<T> Two<T> where T: Foo {}

这不会与错误一起编译:

error[E0277]: cannot add `&'a T` to `&'a T`
  --> src/main.rs:15:1
   |
15 | impl<T> Two<T> where T: Foo {}
   | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ no implementation for `&'a T + &'a T`
   |
   = help: the trait `for<'a> std::ops::Add` is not implemented for `&'a T`
   = help: consider adding a `where for<'a> &'a T: std::ops::Add` bound
note: required by `Foo`
  --> src/main.rs:3:3
   |
3  | /   trait Foo
4  | | where
5  | |     for<'a> &'a Self: Add<Output = Self>,
6  | | {
7  | | }
   | |_^

如果T需要本身具有该要求的Foo,为什么需要该子句?还有其他方法可以创建合并特性以获得更好的效率吗?

0 个答案:

没有答案