确保铁锈的特征实现满足特性

时间:2019-07-11 03:43:05

标签: rust traits

我正在制作特征以定义度量空间中的距离,例如:

trait Metric<T> {
    fn distance(o1: &T, o2: &T) -> f64;
}

,并且我希望任何实现都满足某些属性,例如:

distance(o, o) = 0.0

存在一种强制执行的方法吗?

1 个答案:

答案 0 :(得分:1)

您可以使用trait_tests crate,尽管我确实相信箱子只是一个实验,所以可能会有粗糙的边缘。 具体来说,我无法弄清楚如何实际测试Metric<T>的所有实现,而只能针对具体类型Metric<i32>进行测试。

例如:

use trait_tests::*;

pub trait Metric<T> {
    fn distance(o1: &T, o2: &T) -> f64;
}

#[trait_tests]
pub trait MetricTests: Metric<i32> {
    fn test_distance() {
        // These could possibly be extended using quickcheck or proptest
        assert!(Self::distance(&42, &42) == 0.0);
    }
}

struct CartesianPlane {}

#[test_impl]
impl Metric<i32> for CartesianPlane {
    fn distance(o1: &i32, o2: &i32) -> f64 {
        (*o2 - *o1) as f64
    }
}

然后,cargo test应该包含针对用#[test_impl]注释的特征的实现者的自动生成的测试。

相关问题