[英]How to specify a supertrait for the reference of a trait?
I'd like to create a trait that enforces implementation of the Add
trait for both the type and a reference to the type.我想创建一个特征来强制实现类型和类型引用的Add
特征。 That is, N + N
and &N + &N
should both be implemented if using the NumberTrait shown below.也就是说,如果使用如下所示的 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`
}
You can do something like this:你可以这样做:
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
}
But most likely, you don't need that constraint everywhere, and you could just put where clause on the add_number_ref
function.但最有可能的是,您不需要到处都使用该约束,您可以将 where 子句放在add_number_ref
function 上。
See: https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=b5bdd3633d22ea1e0873d431a6665f9d参见: https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=b5bdd3633d22ea1e0873d431a6665f9d
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.