如何使用现有函数实现实现特征?

时间:2017-08-02 00:10:34

标签: rust

我正在试图找出一个函数Rust将在特征实现中使用哪个版本的规则。具体来说,我希望从我自己的特征中实现here实现的函数。

当我使用函数T定义特征sin时;我希望T Complex64的实现能够引用sin包中num::complex的实现,但尝试这样做会导致无限递归。

这个问题导致我试图找出使调用递归的原因,而不是引用现有的函数。我的测试用例低于(playground link);我已经尝试在现有类型,新类型和通用结构上实现特征,但所有这些情况似乎都正确地转发到现有实现。

Complex64导致递归的特殊之处是什么?有没有办法解决这个问题?

extern crate num;
use num::complex::*;

use std::fmt::Debug;
use std::marker::PhantomData;

// Vanilla struct
struct S { }

// Generic struct
struct G<K> { _g: PhantomData<K> }

// Trait with a function we want to forward to existing implementations
trait T {
    fn sin(self) -> Self;
}

// Existing implementation for vanilla struct
impl S {
    fn sin(self) -> Self { println!("Outside Version"); S {} }
}

// Existing implementation for generic struct
impl<K: Debug> G<K> {
    fn sin(self) -> Self { println!("Outside (generic)"); G { _g: PhantomData } }
}

// Forwarding for vanilla struct
impl T for S {
    fn sin(self) -> Self { self.sin() }
}

// Forwarding for generic struct
impl T for G<f32> {
    fn sin(self) -> Self { self.sin() }
}

// Forwarding for primitive type
impl T for f32 {
    fn sin(self) -> Self { let x = self.sin(); println!("{}", x); x }
}

// Forwarding for externally defined type
// NOTE: for this impl only, we get a warning about unconditional recursion
impl T for Complex64 {
    fn sin(self) -> Self { let x = self.sin(); println!("{}", x); x }
}

// Function to ensure we're using the version of sin defined in T
fn do_sin<K: T>(k: K) {
    k.sin();
}

fn main() {
    let x = S {};
    let y = 1.2f32;
    let z: G<f32> = G { _g: PhantomData };
    let w = Complex64 { re: 1.0, im: 2.0 };
    do_sin(x); // forwarding works
    do_sin(y); // forwarding works
    do_sin(z); // forwarding works
    do_sin(w); // forwarding fails with infinite recursion
}

0 个答案:

没有答案
相关问题