作者热门文章
- c - 在位数组中找到第一个零
- linux - Unix 显示有关匹配两种模式之一的文件的信息
- 正则表达式替换多个文件
- linux - 隐藏来自 xtrace 的命令
可能是一个措辞不佳的问题,但这里有一个例子:
给定这些结构;
pub struct Poll {
_lat: f64,
_lon: f64,
_at: i64,
_heading: f64,
_speed: f64,
}
pub struct Waypoint {
_lat: f64,
_lon: f64,
}
还有这个特质;
pub trait CoordMeasure {
fn dist_to(&self, other: &Self ) -> f64;
}
如何避免像我所做的那样重复此代码?
impl CoordMeasure for Poll {
fn dist_to(&self, other: &Poll) -> f64 {
super::core::distance(self, other)
}
}
impl CoordMeasure for Waypoint {
fn dist_to(&self, other: &Waypoint) -> f64 {
super::core::distance(self, other)
}
}
我有两个调用相同的函数距离。
pub fn distance<T: Coord>(a: &T, b: &T ) -> f64 {
let lat1_rads = (90.0 - a.lat()).to_radians();
let lat2_rads = (90.0 - b.lat()).to_radians();
let lon_rads = (b.lon() - a.lon()).to_radians();
let cos_of_lat1 = lat1_rads.cos();
let cos_of_lat2 = lat2_rads.cos();
let sin_of_lat1 = lat1_rads.sin();
let sin_of_lat2 = lat2_rads.sin();
let cos_of_lons = lon_rads.cos();
let equation = ((cos_of_lat2 * cos_of_lat1) + (sin_of_lat2 * sin_of_lat1 * cos_of_lons)).acos();
6334009.6 * equation
}
这只是重复的一行代码,但在更好的示例中可能会更多。在 C# 中,这段代码将在 Waypoint 和 Poll 派生的抽象类中编写一次。什么是惯用语 Rust如何处理这种情况?
最佳答案
通用实现是可能的:
impl<T: Coord> CoordMeasure for T {
fn dist_to(&self, other: &T) -> f64 {
super::core::distance(self, other)
}
}
但在这种特殊情况下,您应该完全放弃 CoordMeasure
并将其作为默认方法在 Coord
上实现:
trait Coord {
…
fn dist_to(&self, other: &Self) -> f64 {
super::core::distance(self, other) // or move its contents in here
}
}
您可能还想使它能够处理其他类型的 other
(我没有看到任何直接的原因为什么 other
必须是同一类型作为 self
:
fn dist_to<Other: Coord>(&self, other: &Other) -> f64 {
let lat1_rads = (90.0 - self.lat()).to_radians();
let lat2_rads = (90.0 - other.lat()).to_radians();
let lon_rads = (b.lon() - self.lon()).to_radians();
let cos_of_lat1 = lat1_rads.cos();
let cos_of_lat2 = lat2_rads.cos();
let sin_of_lat1 = lat1_rads.sin();
let sin_of_lat2 = lat2_rads.sin();
let cos_of_lons = lon_rads.cos();
let equation = ((cos_of_lat2 * cos_of_lat1) + (sin_of_lat2 * sin_of_lat1 * cos_of_lons)).acos();
6334009.6 * equation
}
关于c# - 如何将 C# 抽象类映射到 Rust?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26326224/
我是一名优秀的程序员,十分优秀!