@@ -144,7 +144,7 @@ use boxed::Box;
144
144
/// # Deref
145
145
///
146
146
/// `String`s implement [`Deref`]`<Target=str>`, and so inherit all of [`str`]'s
147
- /// methods. In addition, this means that you can pass a `String` to any
147
+ /// methods. In addition, this means that you can pass a `String` to a
148
148
/// function which takes a [`&str`] by using an ampersand (`&`):
149
149
///
150
150
/// ```
@@ -160,8 +160,31 @@ use boxed::Box;
160
160
///
161
161
/// This will create a [`&str`] from the `String` and pass it in. This
162
162
/// conversion is very inexpensive, and so generally, functions will accept
163
- /// [`&str`]s as arguments unless they need a `String` for some specific reason.
163
+ /// [`&str`]s as arguments unless they need a `String` for some specific
164
+ /// reason.
164
165
///
166
+ /// In certain cases Rust doesn't have enough information to make this conversion,
167
+ /// known as deref coercion. For example, in this case a string slice implements
168
+ /// a trait and the function takes anything that implements the trait, Rust would
169
+ /// need to make two implicit conversions which Rust doesn't know how to do. The
170
+ /// following example will not compile for that reason.
171
+ ///
172
+ /// ```compile_fail,E0277
173
+ /// trait TraitExample {}
174
+ ///
175
+ /// impl<'a> TraitExample for &'a str {}
176
+ ///
177
+ /// fn example_func<A: TraitExample>(example_arg: A) {}
178
+ ///
179
+ /// fn main() {
180
+ /// let example_string = String::from("example_string");
181
+ /// example_func(&example_string);
182
+ /// }
183
+ /// ```
184
+ ///
185
+ /// What would work in this case is changing the line `example_func(&example_string);`
186
+ /// to `example_func(example_string.to_str());`. This works because we're doing the
187
+ /// conversion explicitly, rather than relying on the implicit conversion.
165
188
///
166
189
/// # Representation
167
190
///
0 commit comments