Skip to content

Commit 7f45460

Browse files
authored
Rework generic fn examples to show monomorphized versions (#2671)
Something I always do when covering generic fns is I like to show the monomorphized versions of `pick` to make it clear to students what generics are doing behind the scenes. In my most recent class I tried going the other way around, showing the monomorphized versions first to more clearly motivate what generics are used for, and I liked the way it went. I think motivating generics by first showing code duplication and then showing how generics allow us to de-duplicate makes for a good teaching flow, and I think it also helps make things clearer to students coming from more dynamic languages that don't have an equivalent to generics. I also changed the `pick` fns to take a `bool` as the first argument because I think that makes things slightly clearer/cleaner, but I'm not married to that change either.
1 parent 8ed932f commit 7f45460

File tree

1 file changed

+30
-8
lines changed

1 file changed

+30
-8
lines changed

src/generics/generic-functions.md

Lines changed: 30 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -8,26 +8,48 @@ Rust supports generics, which lets you abstract algorithms or data structures
88
(such as sorting or a binary tree) over the types used or stored.
99

1010
```rust,editable
11-
/// Pick `even` or `odd` depending on the value of `n`.
12-
fn pick<T>(n: i32, even: T, odd: T) -> T {
13-
if n % 2 == 0 {
14-
even
11+
fn pick<T>(cond: bool, left: T, right: T) -> T {
12+
if cond {
13+
left
1514
} else {
16-
odd
15+
right
1716
}
1817
}
1918
2019
fn main() {
21-
println!("picked a number: {:?}", pick(97, 222, 333));
22-
println!("picked a string: {:?}", pick(28, "dog", "cat"));
20+
println!("picked a number: {:?}", pick(true, 222, 333));
21+
println!("picked a string: {:?}", pick(false, 'L', 'R'));
2322
}
2423
```
2524

2625
<details>
2726

27+
- It can be helpful to show the monomorphized versions of `pick`, either before
28+
talking about the generic `pick` in order to show how generics can reduce code
29+
duplication, or after talking about generics to show how monomorphization
30+
works.
31+
32+
```rust
33+
fn pick_i32(cond: bool, left: i32, right: i32) -> i32 {
34+
if cond {
35+
left
36+
} else {
37+
right
38+
}
39+
}
40+
41+
fn pick_char(cond: bool, left: char, right: char) -> char {
42+
if cond {
43+
left
44+
} else {
45+
right
46+
}
47+
}
48+
```
49+
2850
- Rust infers a type for T based on the types of the arguments and return value.
2951

30-
- In this example we only use the primitive types `i32` and `&str` for `T`, but
52+
- In this example we only use the primitive types `i32` and `char` for `T`, but
3153
we can use any type here, including user-defined types:
3254

3355
```rust,ignore

0 commit comments

Comments
 (0)