Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Rework generic fn examples to show monomorphized versions #2671

Merged
merged 3 commits into from
Mar 3, 2025
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
38 changes: 30 additions & 8 deletions src/generics/generic-functions.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,26 +8,48 @@ Rust supports generics, which lets you abstract algorithms or data structures
(such as sorting or a binary tree) over the types used or stored.

```rust,editable
/// Pick `even` or `odd` depending on the value of `n`.
fn pick<T>(n: i32, even: T, odd: T) -> T {
if n % 2 == 0 {
even
fn pick<T>(cond: bool, left: T, right: T) -> T {
if cond {
left
} else {
odd
right
}
}

fn main() {
println!("picked a number: {:?}", pick(97, 222, 333));
println!("picked a string: {:?}", pick(28, "dog", "cat"));
println!("picked a number: {:?}", pick(true, 222, 333));
println!("picked a string: {:?}", pick(false, 'L', 'R'));
}
```

<details>

- It can be helpful to show the monomorphized versions of `pick`, either before
talking about the generic `pick` in order to show how generics can reduce code
duplication, or after talking about generics to show how monomorphization
works.

```rust
fn pick_i32(cond: bool, left: i32, right: i32) -> i32 {
if cond {
left
} else {
right
}
}

fn pick_char(cond: bool, left: char, right: char) -> char {
if cond {
left
} else {
right
}
}
```

- Rust infers a type for T based on the types of the arguments and return value.

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

```rust,ignore
Expand Down