简体   繁体   English

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

[英]Ensure that a trait implementation in rust satisfy properties

I am making a trait to define a distance in a metric space like: 我正在制作一个特征来定义度量空间中的距离,例如:

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

and I want that any implementation satisfy some properties, for example: 并且我希望任何实现都满足某些属性,例如:

distance(o, o) = 0.0

Exist a way in rust to enforce that? 存在一种强制执行的方法吗?

You can use the trait_tests crate , though I do believe the crate is merely an experiment, so there may be rough edges. 您可以使用trait_tests板条箱 ,尽管我确实认为该板条箱仅仅是实验,所以可能会有粗糙的边缘。 Specifically, I couldn't figure out how to actually test all implementations of Metric<T> , rather only for a concrete type, Metric<i32> . 具体来说,我无法弄清楚如何实际测试Metric<T>所有实现,而只能针对具体类型Metric<i32>

For your example: 例如:

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
    }
}

Then cargo test should include the auto-generated test for the implementors of the trait that are annotated with #[test_impl] . 然后, cargo test应包括针对该特性的实现者的自动生成的测试,并用#[test_impl]进行注释。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM