你能为多种类型实现通用结构吗?

时间:2015-02-03 04:24:23

标签: 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);
    }

    // ...
}

我开始添加f64的实现:

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

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

src/impls/dit.rs:186:7: 196:4 error: duplicate definition of value `new`
src/impls/dit.rs:186   pub fn new(n:usize) -> Result<Dit<f64>, FFTError> {
src/impls/dit.rs:187     if 2.pow((n as f64).log2() as usize) != n {
src/impls/dit.rs:188       return Err(FFTError::InvalidLength);
src/impls/dit.rs:189     }
src/impls/dit.rs:190     let rtn = Dit {
src/impls/dit.rs:191       n: n,
                     ...
src/impls/dit.rs:110:7: 120:4 note: first definition of value `new` here
src/impls/dit.rs:110   pub fn new(n:usize) -> Result<Dit<f32>, FFTError> {
src/impls/dit.rs:111     if 2.pow((n as f64).log2() as usize) != n {
src/impls/dit.rs:112       return Err(FFTError::InvalidLength);
src/impls/dit.rs:113     }
src/impls/dit.rs:114     let rtn = Dit {
src/impls/dit.rs:115       n: n,

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

我做错了什么?

1 个答案:

答案 0 :(得分:3)

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

但是有一些工作结构如:

impl<T> Dit<T> where T: Float {

或:

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

impl DitTrait for Dit<f32> { ... }
impl DitTrait for Dit<f64> { ... }
相关问题