From b4f5a4542472193cfd7c98c2a8bbb43b009df17f Mon Sep 17 00:00:00 2001 From: LukeMathWalker <20745048+LukeMathWalker@users.noreply.github.com> Date: Tue, 14 May 2024 11:00:59 +0200 Subject: [PATCH] Elaborate further on `Add`. --- book/src/04_traits/09_assoc_vs_generic.md | 30 ++++++++++++++++++++--- 1 file changed, 27 insertions(+), 3 deletions(-) diff --git a/book/src/04_traits/09_assoc_vs_generic.md b/book/src/04_traits/09_assoc_vs_generic.md index 368f67b..f6d25c4 100644 --- a/book/src/04_traits/09_assoc_vs_generic.md +++ b/book/src/04_traits/09_assoc_vs_generic.md @@ -71,14 +71,38 @@ It uses both mechanisms: - it has a generic parameter, `RHS` (right-hand side), which defaults to `Self` - it has an associated type, `Output`, the type of the result of the addition -`RHS` is a generic parameter to allow for different types to be added together. -For example: +### `RHS` + +`RHS` is a generic parameter to allow for different types to be added together. +For example, you'll find these two implementation in the standard library: + +```rust +impl Add for u32 { + type Output = u32; + + fn add(self, rhs: u32) -> u32 { + // [...] + } +} + +impl Add<&u32> for u32 { + type Output = u32; + + fn add(self, rhs: &u32) -> u32 { + // [...] + } +} +``` + +This allows the following code to compile: ```rust let x = 5u32 + &5u32 + 6u32; ``` -works because `u32` implements `Add<&u32>` _as well as_ `Add`. +because `u32` implements `Add<&u32>` _as well as_ `Add`. + +### `Output` `Output`, on the other hand, **must** be uniquely determined once the types of the operands are known. That's why it's an associated type instead of a second generic parameter. -- 2.45.2