确保 rust 中的特征实现满足属性
Ensure that a trait implementation in rust satisfy properties
我正在制作一个特征来定义度量中的距离 space 例如:
trait Metric<T> {
fn distance(o1: &T, o2: &T) -> f64;
}
并且我希望任何实现都满足某些属性,例如:
distance(o, o) = 0.0
Rust 中是否存在强制执行此操作的方法?
您可以使用 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
应该包括 auto-generated 对带有 #[test_impl]
注释的特征实现者的测试。
我正在制作一个特征来定义度量中的距离 space 例如:
trait Metric<T> {
fn distance(o1: &T, o2: &T) -> f64;
}
并且我希望任何实现都满足某些属性,例如:
distance(o, o) = 0.0
Rust 中是否存在强制执行此操作的方法?
您可以使用 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
应该包括 auto-generated 对带有 #[test_impl]
注释的特征实现者的测试。