您可以为多种类型实现通用结构吗?

Dou*_*oug 2 rust

我有一个Dit<T>实现 T 的 FFT 的通用结构:

struct Dit<T> {
    n: usize,
    exponents: Bin<f32, Complex<T>>,
    tmp: Option<Vec<Complex<T>>>,
}

impl Dit<f32> {
    /// Create a new instance
    ///
    /// Notice that the number of samples that will be processed by an instance
    /// is always fixed, because the exponent values are precalculated.
    ///
    /// # Parameters
    /// - `n` The number of samples this operator can process, eg. 1024
    pub fn new(n: usize) -> Result<Dit<f32>, FFTError> {
        if 2.pow((n as f64).log2() as usize) != n {
            return Err(FFTError::InvalidLength);
        }

        let rtn = Dit {
            n: n,
            exponents: Bin::new(),
            tmp: None,
        }.pregen();

        return Ok(rtn);
    }

    // ...
}
Run Code Online (Sandbox Code Playgroud)

我开始添加以下实现f64

impl Dit<f64> {
    pub fn new(n: usize) -> Result<Dit<f64>, FFTError> {
        unimplemented!()
    }
    // ...
}
Run Code Online (Sandbox Code Playgroud)

...我遇到了这些错误:

struct Dit<T> {
    n: usize,
    exponents: Bin<f32, Complex<T>>,
    tmp: Option<Vec<Complex<T>>>,
}

impl Dit<f32> {
    /// Create a new instance
    ///
    /// Notice that the number of samples that will be processed by an instance
    /// is always fixed, because the exponent values are precalculated.
    ///
    /// # Parameters
    /// - `n` The number of samples this operator can process, eg. 1024
    pub fn new(n: usize) -> Result<Dit<f32>, FFTError> {
        if 2.pow((n as f64).log2() as usize) != n {
            return Err(FFTError::InvalidLength);
        }

        let rtn = Dit {
            n: n,
            exponents: Bin::new(),
            tmp: None,
        }.pregen();

        return Ok(rtn);
    }

    // ...
}
Run Code Online (Sandbox Code Playgroud)

我很困惑。我的印象是,对于通用的Foo<T>,实现Foo<Bar1>是与 的实现不同的具体实例Foo<Bar2>。因此,我的印象是,对于每个具体实例,我可以有不同的方法实例。

我究竟做错了什么?

swi*_*ard 5

我认为用这样的语法不可能解决你的任务(至少,我在 Rust 参考书中找不到任何例子)。

但有一些工作结构,例如:

impl<T> Dit<T> where T: Float {
Run Code Online (Sandbox Code Playgroud)

或者:

trait DitTrait {
    fn new(n: usize) -> Result<Self, FFTError>;
}

impl DitTrait for Dit<f32> { ... }
impl DitTrait for Dit<f64> { ... }
Run Code Online (Sandbox Code Playgroud)