From: LukeMathWalker <20745048+LukeMathWalker@users.noreply.github.com> Date: Fri, 24 May 2024 10:12:51 +0000 (+0200) Subject: Explain that generic parameters don't have to be single letters. X-Git-Url: http://git.euphorik.ch/?a=commitdiff_plain;h=5977b1c51ba26b979065cd77d886a8a7549f365c;p=rust_exercises.git Explain that generic parameters don't have to be single letters. --- diff --git a/book/src/04_traits/05_trait_bounds.md b/book/src/04_traits/05_trait_bounds.md index af1808b..a118b1b 100644 --- a/book/src/04_traits/05_trait_bounds.md +++ b/book/src/04_traits/05_trait_bounds.md @@ -116,10 +116,11 @@ help: consider restricting type parameter `T` Without trait bounds, the compiler doesn't know what `T` **can do**. It doesn't know that `T` has an `is_even` method, and it doesn't know how to format `T` for printing. +From the compiler point of view, a bare `T` has no behaviour at all. Trait bounds restrict the set of types that can be used by ensuring that the behaviour required by the function body is present. -## Inlining trait bounds +## Syntax: inlining trait bounds All the examples above used a **`where` clause** to specify trait bounds: @@ -144,6 +145,23 @@ fn print_if_even(n: T) { } ``` +## Syntax: meaningful names + +In the examples above, we used `T` as the type parameter name. This is a common convention when a function has +only one type parameter. +Nothing stops you from using a more meaningful name, though: + +```rust +fn print_if_even(n: Number) { + // [...] +} +``` + +It is actually **desirable** to use meaningful names when there are multiple type parameters at play or when the name +`T` doesn't convey enough information about the type's role in the function. +Maximize clarity and readability when naming type parameters, just as you would with variables or function parameters. +Follow Rust's conventions though: use camel case for type parameter names. + ## The function signature is king You may wonder why we need trait bounds at all. Can't the compiler infer the required traits from the function's body?