Types 使用where子句实现Trait:实现一个简单的where子句
我一直试图通过学习生锈,但却遇到了一堵具有以下特征的墙:Types 使用where子句实现Trait:实现一个简单的where子句,types,rust,traits,Types,Rust,Traits,我一直试图通过学习生锈,但却遇到了一堵具有以下特征的墙: // 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
// 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);
}
仍然-代码没有编译。似乎由于T
被解引用,我需要为解引用的值添加边界,但我找不到任何示例来说明如何执行此操作
error[E0369]:二进制操作“%”不能应用于类型“%T”`
-->src\koans/traits.rs:142:13
|
142 |自我%2==0
| ^^^^^^^^
|
=注意:`&T可能缺少`std::ops::Rem`的实现`
简而言之:解决这个koan的惯用方法是什么?我想你可能误解了这个练习的意图。你想要的是:
fn main() {
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)
where T: IsEvenOrOdd {
assert!(!x.is_even());
assert!(y.is_even());
}
asserts(num_one, num_two);
}
此错误告诉我们,要调用
is_even
方法,必须实现IsEvenOrOdd
。您发布的示例顶部的注释表示在函数上使用where
子句。将where
子句添加到函数断言可以解决问题并完成练习 “目标似乎是通过创建IsEvenOrOdd实现的通用版本来完成这段代码。”是吗?我假设目标只是添加一个where
子句,以便代码能够编译;要解决koan,请将中的T:IsEvenOrOdd
添加到fn断言中
。
fn main() {
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)
where T: IsEvenOrOdd {
assert!(!x.is_even());
assert!(y.is_even());
}
asserts(num_one, num_two);
}