【发布时间】:2019-05-16 16:16:31
【问题描述】:
我一直在尝试通过rust-koans 学习 Rust,但遇到了具有以下 trait koan 的墙:
// There is an alternate syntax for placing trait bounds on a function, the
// where clause. Let's revisit a previous example, this time using 'where'.
#[test]
fn where_clause() {
let num_one: u16 = 3;
let num_two: u16 = 4;
trait IsEvenOrOdd {
fn is_even(&self) -> bool;
}
impl IsEvenOrOdd for u16 {
fn is_even(&self) -> bool {
self % 2 == 0
}
}
fn asserts<T>(x: T, y: T) {
assert!(!x.is_even());
assert!(y.is_even());
}
asserts(num_one, num_two);
}
似乎目标是通过创建IsEvenOrOdd 实现的通用版本来完成此代码。在这种情况下,泛型类型应该有两个界限,余数运算符和PartialEq 运算符。因为余数右边和等价右边都是整数,所以我最终写了下面的意大利面条代码:
use std::ops::Rem;
impl<T> IsEvenOrOdd for T
where
T: Rem<u16> + Rem,
<T as Rem<u16>>::Output: PartialEq<u16>,
{
fn is_even(&self) -> bool {
self % 2 == 0
}
}
仍然 - 代码无法编译。似乎由于 T 被取消引用,我需要为取消引用的值添加边界,但我找不到任何示例说明如何做到这一点。
error[E0369]: binary operation `%` cannot be applied to type `&T`
--> src\koans/traits.rs:142:13
|
142 | self % 2 == 0
| ^^^^^^^^
|
= note: an implementation of `std::ops::Rem` might be missing for `&T`
简而言之:解决这个公案的惯用 Rust 方法是什么?
【问题讨论】:
-
“似乎目标是通过创建 IsEvenOrOdd 实现的通用版本来完成此代码。”是吗?我假设目标只是添加一个
where子句以便代码编译。 -
我同意;要解决公案,请将
where T: IsEvenOrOdd添加到fn asserts。