Skip to content

Commit 556b081

Browse files
committed
Using operator traits in generic structs
1 parent 0e92165 commit 556b081

File tree

2 files changed

+58
-0
lines changed

2 files changed

+58
-0
lines changed

src/doc/trpl/operators-and-overloading.md

Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -81,3 +81,55 @@ will let you do this:
8181
let p: Point = // ...
8282
let x: f64 = p + 2i32;
8383
```
84+
85+
# Using operator traits in generic structs
86+
87+
Now that we know how operator traits are defined, we can define our `HasArea`
88+
trait and `Square` struct from the [traits chapter][traits] more generically:
89+
90+
[traits]: traits.html
91+
92+
```rust
93+
use std::ops::Mul;
94+
95+
trait HasArea<T> {
96+
fn area(&self) -> T;
97+
}
98+
99+
struct Square<T> {
100+
x: T,
101+
y: T,
102+
side: T,
103+
}
104+
105+
impl<T> HasArea<T> for Square<T>
106+
where T: Mul<Output=T> + Copy {
107+
fn area(&self) -> T {
108+
self.side * self.side
109+
}
110+
}
111+
112+
fn main() {
113+
let s = Square {
114+
x: 0.0f64,
115+
y: 0.0f64,
116+
side: 12.0f64,
117+
};
118+
119+
println!("Area of s: {}", s.area());
120+
}
121+
```
122+
123+
For `HasArea` and `Square`, we just declare a type parameter `T` and replace
124+
`f64` with it. The `impl` needs more involved modifications:
125+
126+
```ignore
127+
impl<T> HasArea<T> for Square<T>
128+
where T: Mul<Output=T> + Copy { ... }
129+
```
130+
131+
The `area` method requires that we can multiply the sides, so we declare that
132+
type `T` must implement `std::ops::Mul`. Like `Add`, mentioned above, `Mul`
133+
itself takes an `Output` parameter: since we know that numbers don't change
134+
type when multiplied, we also set it to `T`. `T` must also support copying, so
135+
Rust doesn't try to move `self.side` into the return value.

src/doc/trpl/traits.md

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -199,7 +199,13 @@ equality.
199199

200200
[PartialEq]: ../core/cmp/trait.PartialEq.html
201201

202+
Here we defined a new struct `Rectangle` that accepts numbers of any
203+
precision—really, objects of pretty much any type—as long as they can be
204+
compared for equality. Could we do the same for our `HasArea` structs, `Square`
205+
and `Circle`? Yes, but they need multiplication, and to work with that we need
206+
to know more about [operator traits][operators-and-overloading].
202207

208+
[operators-and-overloading]: operators-and-overloading.html
203209

204210
# Rules for implementing traits
205211

0 commit comments

Comments
 (0)