Skip to content

Commit 2c975a2

Browse files
committed
generics: add explanatory commentary to solution
This commentary, written by Gemini, focuses on aspects of the solution that differ from the baseline languages (C/Java/Python), highlighting Rust-specific idioms and concepts.
1 parent 0867e24 commit 2c975a2

File tree

1 file changed

+21
-0
lines changed

1 file changed

+21
-0
lines changed

src/generics/solution.md

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,3 +3,24 @@
33
```rust,editable
44
{{#include exercise.rs:solution}}
55
```
6+
7+
- **Generic Function:** `min` is a generic function that takes two arguments of
8+
type `T`.
9+
- **Trait Bounds:** The syntax `<T: Ord>` specifies that `T` must implement the
10+
`Ord` trait. This is necessary because not all types can be compared (e.g.,
11+
floating-point numbers in Rust only implement `PartialOrd` due to `NaN`).
12+
- **`Ord` Trait:** The `Ord` trait provides the `cmp` method, which compares two
13+
values and returns an `Ordering`.
14+
- **`Ordering` Enum:** The result of `cmp` is an enum with variants `Less`,
15+
`Equal`, and `Greater`. We use `match` to handle these cases.
16+
17+
<details>
18+
19+
- Mention that for floating point numbers, `f64` does not implement `Ord`, so
20+
this function would not work for them. This is a deliberate design choice in
21+
Rust to handle `NaN` correctly (NaN != NaN). To handle floats, one would
22+
typically use `PartialOrd` or a wrapper type.
23+
- Alternatively, `l <= r` works if we use `T: PartialOrd`. However, `Ord` is
24+
stricter and guarantees a total order, which `cmp` relies on.
25+
26+
</details>

0 commit comments

Comments
 (0)