我想创建一个特征,以强制实现类型和对类型的引用的Add
特征的实现。也就是说,如果使用下面显示的NumberTrait,则应同时实现N + N
和&N + &N
。
use std::ops::Add;
// I think a supertrait needs to be added to NumberTrait,
// something like &Add<Output = Self>, but I don't know
// the correct syntax
pub trait NumberTrait: Sized + Add<Output = Self> {}
fn add_number<N: NumberTrait>(a: N, b: N) -> N {
a + b
}
fn add_number_ref<N: NumberTrait>(a: &N, b: &N) -> N {
a + b // compiler error occurs in this line: an implementation of `std::ops::Add` might be missing for `&N`
}
答案 0 :(得分:0)
您可以执行以下操作:
use std::ops::Add;
pub trait NumberTrait: Sized + Add<Output = Self>
where
for<'a> &'a Self: Add<Output = Self>,
{
}
fn add_number<N: NumberTrait>(a: N, b: N) -> N
where
for<'a> &'a N: Add<Output = N>,
{
a + b
}
fn add_number_ref<N: NumberTrait>(a: &N, b: &N) -> N
where
for<'a> &'a N: Add<Output = N>,
{
a + b
}
但是最有可能的是,您不需要在所有地方都使用该约束,而只需在add_number_ref
函数上放置where子句即可。