Generics 如何为特征的引用指定超级特征?

Generics 如何为特征的引用指定超级特征?,generics,rust,traits,Generics,Rust,Traits,我想为类型和类型引用创建一个trait,它强制实现Addtrait。也就是说,如果使用如下所示的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 trai

我想为类型和类型引用创建一个trait,它强制实现
Add
trait。也就是说,如果使用如下所示的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`
}
使用std::ops::Add;
//我认为需要在NumberTrait中添加一个超级特性,
//类似于&Add,但我不知道
//正确的语法
pub trait NumberTrait:size+Add{}
fn添加编号(a:N,b:N)->N{
a+b
}
fn添加编号\u参考(a:&N,b:&N)->N{
a+b//此行发生编译器错误:`&N可能缺少`std::ops::Add`的实现`
}

您可以执行以下操作:

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
}

使用std::ops::Add;
发布特征编号Rait:大小+添加
哪里
为了
哪里
为了
哪里

对于您可以执行以下操作:

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
}

使用std::ops::Add;
发布特征编号Rait:大小+添加
哪里
为了
哪里
为了
哪里

因为,你不能,你看不到这样做有什么好处,只是噪音。谢谢@Thayne.In
add\u number\u ref
,你不需要HRTB,只需要做
fn add\u number\u refI我看不到这样做有什么好处,只是噪音。谢谢@Thayne.In
add\u number\u ref
,您不需要HRTB,只需执行
fn add\u number\u ref即可