gpt4 book ai didi

rust - 如何比较 Rectangle 的形状是否相等?

转载 作者:行者123 更新时间:2023-11-29 08:25:11 24 4
gpt4 key购买 nike

给定

struct Rectangle<T, U> {
x: T,
y: U,
}

let first = Rectangle { x: 3.2, y: 1 };
let second = Rectangle { x: 1, y: 3.2 };
let third = Rectangle { x: 3, y: 1 };

我如何声明/实现保险箱 fn same_shape_as(&self, …) -> bool对于 first, first 返回真, first, secondsecond, first , 但对于 first, third 为假? (不一定要寻找完整的实现,而只是涉及哪些语法/概念。)例如,是否有某种方式可以 match属性类型是否相等,或者在尝试比较两个值之前检查两个值是否具有可比性?

澄清一下,朴素的 Python(是的,我知道鸭子类型)实现可能如下所示:

def same_shape_as(self, other):
if type(self.x) == type(other.x) and type(self.y) == type(other.y):
return self.x == other.x and self.y == other.y
elif type(self.x) == type(other.y) and type(self.y) == type(other.x):
return self.x == other.y and self.y == other.x
else:
return False

最佳答案

虽然可以通过使用 Any

在某种程度上模仿动态类型的语言
fn compare<T, U, V, W>(a: &Rect<T, U>, b: &Rect<V, W>) -> bool
where
T: Any + PartialEq + 'static, U: Any + PartialEq + 'static,
V: Any + 'static, W: Any + 'static,
{
if Any::is::<T>(&b.x) && Any::is::<U>(&b.y) {
Some(&a.x) == Any::downcast_ref::<T>(&b.x) &&
Some(&a.y) == Any::downcast_ref::<U>(&b.y)
} else if Any::is::<T>(&b.y) && Any::is::<U>(&b.x) {
Some(&a.x) == Any::downcast_ref::<T>(&b.y) &&
Some(&a.y) == Any::downcast_ref::<U>(&b.x)
} else {
false
}
}

我会通过实现 PartialEq 和一个简单的辅助函数来交换结构的元素。

struct Rect<T, U> {
x: T,
y: U,
}

impl<T, U> Rect<T, U> {
// Reverse the order of structure fields
// References allow the use of non-copiable types T and U
fn rev(&self) -> Rect<&U, &T> {
Rect {
x: &self.y,
y: &self.x,
}
}
}

impl<T, U> PartialEq for Rect<T, U>
where
T: PartialEq,
U: PartialEq,
{
fn eq(&self, other: &Self) -> bool {
self.x == other.x && self.y == other.y
}
}

// Allows to compare Rect<T, U> and Rect<&T, &U>
impl<'a, T, U> PartialEq<Rect<&'a T, &'a U>> for Rect<T, U>
where
T: PartialEq,
U: PartialEq,
{
fn eq(&self, other: &Rect<&'a T, &'a U>) -> bool {
&self.x == other.x && &self.y == other.y
}
}

fn main() {
let first = Rect { x: 3.2, y: 1 };
let second = Rect { x: 1, y: 3.2 };
let third = Rect { x: 3, y: 1 };
let fourth = Rect { x: 3.1, y: 2 };


assert_eq!(first == second.rev(), true);
assert_eq!(first == fourth, false);
// assert_eq!(first == third, false); // Compilation error
assert_eq!(first == first, true);
}

Playground

关于rust - 如何比较 Rectangle<T, U> 的形状是否相等?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47362306/

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