gpt4 book ai didi

c# - 如何将 C# 抽象类映射到 Rust?

转载 作者:太空狗 更新时间:2023-10-30 01:35:18 24 4
gpt4 key购买 nike

可能是一个措辞不佳的问题,但这里有一个例子:

给定这些结构;

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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com