[英]How do you map a c# abstract class to Rust?
可能是措辭不好的問題,但這里舉個例子:
鑒於這些結構;
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
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.