Rust 您能否为多种类型实现通用结构?
我有一个通用结构Dit,它实现了T的FFT:Rust 您能否为多种类型实现通用结构?,rust,Rust,我有一个通用结构Dit,它实现了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 num
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);
}
// ...
}
…我会犯这样的错误:
src/impls/dit.rs:186:7:196:4错误:值“new”的定义重复`
src/impls/dit.rs:186 pub fn new(n:usize)->结果{
src/impls/dit.rs:187if 2.pow((n作为f64.log2()作为usize)!=n{
src/impls/dit.rs:188返回错误(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注:此处是值'new'的第一个定义
src/impls/dit.rs:110 pub fn new(n:usize)->结果{
src/impls/dit.rs:111如果2.pow((n作为f64.log2()作为usize)!=n{
src/impls/dit.rs:112返回错误(FFTError::InvalidLength);
src/impls/dit.rs:113}
src/impls/dit.rs:114让rtn=dit{
src/impls/dit.rs:115 n:n,
我感到困惑。我的印象是,对于泛型Foo
,实现Foo
与Foo
的实现是不同的具体实例。因此,我的印象是,我可以为每个具体实例提供不同的方法实例
我做错了什么?我认为用这种语法解决你的任务是不可能的(至少,我在参考书中找不到任何例子) 但也有一些工作结构,如:
impl<T> Dit<T> where T: Float {
impl Dit,其中T:Float{
或:
trait-DitTrait{
fn新(n:usize)->结果;
}
Dit{…}的impl DITTRACIT
Dit{…}的impl DITTRACIT
允许多个impl
s,但任何给定方法只有一个定义。
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> { ... }