I'd like to create a trait that enforces implementation of the Add
trait for both the type and a reference to the type. That is, N + N
and &N + &N
should both be implemented if using the NumberTrait shown below.
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.