Problem using a generic implementation of binary operators
⚓ Rust 📅 2026-02-12 👤 surdeus 👁️ 5The following example:
// Sub
use std::ops::Sub;
//
// FloatType
#[derive(Debug)]
struct FloatType<F>(pub F);
//
// &FloatType<F> - &FloatType<F>
impl<F> Sub< &FloatType<F> > for &FloatType<F>
where
for<'a> &'a F : Sub<&'a F, Output=F>,
{
type Output = FloatType<F>;
fn sub(self, rhs : &FloatType<F> ) -> FloatType<F> {
FloatType( (self.0).sub(&rhs.0) )
}
}
//
// difference
fn difference<V>(x : &V, y : &V) -> V
where
for<'a> &'a V : std::ops::Sub<&'a V, Output=V> ,
{ x - y
}
//
// main
fn main() {
let x = FloatType::<f32>( 1f32 );
let y = FloatType::<f32>( 2f32 );
let z = difference(&x, &y);
println!("z = {:?}", z);
}
results in the following compiler output:
... snip ...
= help: consider increasing the recursion limit by adding a `#![recursion_limit = "256"]` attribute to your crate (`package`)
note: required for `&'a FloatType<std::collections::HashSet<_, _>>` to implement `for<'a> std::ops::Sub`
--> src/main.rs:9:9
|
9 | impl<F> Sub< &FloatType<F> > for &FloatType<F>
| ^^^^^^^^^^^^^^^^^^^^ ^^^^^^^^^^^^^
10 | where
11 | for<'a> &'a F : Sub<&'a F, Output=F>,
| -------- unsatisfied trait bound introduced here
... snip ...
The problem goes away if I change the implementation for the Sub trait to
impl Sub< &FloatType<f32> > for &FloatType<f32>
{
type Output = FloatType<f32>;
fn sub(self, rhs : &FloatType<f32> ) -> FloatType<f32> {
FloatType( (self.0).sub(&rhs.0) )
}
}
Is there a generic way to implemen the Sub trait for this case ?
4 posts - 4 participants
🏷️ Rust_feed