Conflicting implementation of trait (generics)

51 Views Asked by At
// std::cmp::PartialOrd is required for the comparison with T::zero(), but Complex does not implement it
impl<T> std::fmt::Display for Polynomial<T>
where
    T: Num + Clone + std::ops::Neg<Output = T> + std::cmp::PartialOrd + std::fmt::Display,
{
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        let mut formatted_string: String = String::new();
        let mut is_first_term: bool = true;

        for (degree, coefficient) in self.coefficients.iter().enumerate().rev() {
            if coefficient != &T::zero() {
                let mut coefficient: T = coefficient.clone();
                let is_neg: bool = coefficient < T::zero();
                let sign: &str = if is_neg {
                    coefficient = -coefficient;
                    "- "
                } else {
                    "+ "
                };

                if is_first_term {
                    if is_neg {
                        formatted_string.push_str(sign);
                    }
                    is_first_term = false;
                } else {
                    formatted_string.push(' ');
                    formatted_string.push_str(sign);
                }

                let formatted: String = match degree {
                    0 => format!("{}", coefficient),
                    1 => format!("{}x", coefficient),
                    _ => format!("{}x^{}", coefficient, degree),
                };

                formatted_string.push_str(&formatted);
            }
        }

        write!(f, "{}", formatted_string)
    }
}

// Why does this not work?
impl std::fmt::Display for Polynomial<num::Complex<f64>> {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        // Implement custom formatting for Polynomial<num::Complex<f64>> here
        write!(f, "Your custom formatting for Complex<f64> polynomials")
    }
}

Complete code: https://pastebin.com/Cari6TWF

Error message: conflicting implementations of trait `std::fmt::Display` for type `Polynomial<num::Complex<f64>>` upstream crates may add a new impl of trait `std::cmp::PartialOrd` for type `num::Complex<f64>` in future versions

Because Complex<T> doesn't implement std::cmp::PartialOrd I didn't expect the second impl to interfere with the first one.

I looked into the following answer as well: Conflicting implementations of trait in Rust but it doesn't seem to help as I need to implement it specifically for Complex<T>

0

There are 0 best solutions below