From: LukeMathWalker <20745048+LukeMathWalker@users.noreply.github.com> Date: Tue, 14 May 2024 09:00:59 +0000 (+0200) Subject: Elaborate further on `Add`. X-Git-Url: http://git.euphorik.ch/?a=commitdiff_plain;h=b4f5a4542472193cfd7c98c2a8bbb43b009df17f;p=rust_exercises.git Elaborate further on `Add`. --- 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.