【问题标题】:Can you implement a generic struct for multiple types?你可以为多种类型实现一个通用结构吗?
【发布时间】:2015-02-03 04:24:22
【问题描述】:

我有一个通用结构 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&lt;T&gt;,实现Foo&lt;Bar1&gt; 是与Foo&lt;Bar2&gt; 实现不同的具体实例。因此,我的印象是每个具体实例可以有不同的方法实例。

我做错了什么?

【问题讨论】:

  • 允许有多个impls,但任何给定方法只能定义一个。

标签: rust


【解决方案1】:

我认为用这样的语法解决你的任务是不可能的(至少,我在 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> { ... }

【讨论】:

    猜你喜欢
    • 2016-08-08
    • 2010-09-09
    • 1970-01-01
    • 1970-01-01
    • 2014-02-11
    • 1970-01-01
    • 2015-05-01
    • 2020-09-03
    • 1970-01-01
    相关资源
    最近更新 更多