Skip to content

Commit b298a58

Browse files
authored
Update String Deref to explain why using &String does not always work
1 parent f2a5af7 commit b298a58

File tree

1 file changed

+25
-2
lines changed

1 file changed

+25
-2
lines changed

src/liballoc/string.rs

Lines changed: 25 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -144,7 +144,7 @@ use boxed::Box;
144144
/// # Deref
145145
///
146146
/// `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
148148
/// function which takes a [`&str`] by using an ampersand (`&`):
149149
///
150150
/// ```
@@ -160,8 +160,31 @@ use boxed::Box;
160160
///
161161
/// This will create a [`&str`] from the `String` and pass it in. This
162162
/// 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.
164165
///
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.
165188
///
166189
/// # Representation
167190
///

0 commit comments

Comments
 (0)