Rust: multiplication of Complex with arbitrary number types

  Kiến thức lập trình

I have some struct struct MyStruct { coeff: Complex<f64>, other_data ... } for which I would like to implement scalar multiplication with any number type (real or Complex, float or integer). My difficulty is, that neither primitive types nor Complex natively supports multiplication of integers with floats, but that also casting, e.g., i32 to Complex<f64> with as seems to not be supported.

The solution I came up with was to define my own Into trait and implement it via macro for all primitive and Complex number types:

use num::complex::Complex;
use std::ops::Mul;

trait IntoComplex {
    fn into_complex(&self) -> Complex<f64>;
}

macro_rules! impl_into_complex {
    ( $( $t:ty ),+ ) => {
        $(
            impl IntoComplex for $t {
                fn into_complex(&self) -> Complex<f64> {
                    let re = *self as f64;
                    Complex::new(re, 0.0)
                }
            }
            impl IntoComplex for Complex<$t> {
                fn into_complex(&self) -> Complex<f64> {
                    let re = self.re as f64;
                    let im = self.im as f64;
                    Complex::new(re, im)
                }
            }
        )+
    }
}
impl_into_complex!(f64, f32, i64, i32, i16, i8, u64, u32, u16, u8);

Then I can also overload the multiplication operator for my struct:

impl<T> Mul<T> for MyStruct where T: IntoComplex {
    type Output = MyStruct;
    fn mul(self, rhs: T) -> MyStruct {
        MyStruct { coeff: self.coeff * rhs.into_complex() }
    }
}

Is there really no native way in num::complex to do this, and is there a better way than this?

LEAVE A COMMENT