Skip to content

Commit 18ec95b

Browse files
Mention the T: Trait shortcut to where clauses
1 parent 37f78ae commit 18ec95b

File tree

1 file changed

+14
-1
lines changed

1 file changed

+14
-1
lines changed

src/language/generics.md

Lines changed: 14 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -73,12 +73,25 @@ impl<T> Timestamped<T> {
7373
}
7474

7575
impl<T> PartialEq for Timestamped<T>
76-
where T: PartialEq {
76+
where
77+
T: PartialEq,
78+
{
79+
fn eq(&self, other: &Self) -> bool {
80+
self.value == other.value && self.timestamp == other.timestamp
81+
}
82+
}
83+
```
84+
85+
A shortcut for `where` clauses that exists in Rust is constraining the parameters
86+
directly at their declaration:
87+
```rust
88+
impl<T: PartialEq> PartialEq for Timestamped<T> {
7789
fn eq(&self, other: &Self) -> bool {
7890
self.value == other.value && self.timestamp == other.timestamp
7991
}
8092
}
8193
```
94+
Although `where` clauses are somewhat more powerful, since they can constrain arbitrary types (e.g. `i32: PartialEq<T>`).
8295

8396
Generic type constraints are called [bounds][bounds.rs] in Rust.
8497

0 commit comments

Comments
 (0)