Skip to content

Commit 49597fc

Browse files
committed
book: explanation that String -> &str coercion doesn't happen for &str traits
1 parent 38a97be commit 49597fc

File tree

1 file changed

+13
-0
lines changed

1 file changed

+13
-0
lines changed

src/doc/trpl/strings.md

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -49,6 +49,18 @@ fn main() {
4949
}
5050
```
5151

52+
This coercion does not happen for functions that accept one of `&str`’s traits
53+
instead of `&str`. For example, [`TcpStream::connect`][connect] has a parameter
54+
of type `ToSocketAddrs`. A `&str` is okay but a `String` must be explicitly
55+
converted using `&*`.
56+
57+
```rust
58+
TcpStream::connect("192.168.0.1:3000"); // &str parameter
59+
60+
let addr_string = "192.168.0.1:3000".to_string();
61+
TcpStream::connect(&*addr_string); // convert addr_string to &str
62+
```
63+
5264
Viewing a `String` as a `&str` is cheap, but converting the `&str` to a
5365
`String` involves allocating memory. No reason to do that unless you have to!
5466

@@ -127,3 +139,4 @@ This is because `&String` can automatically coerce to a `&str`. This is a
127139
feature called ‘[`Deref` coercions][dc]’.
128140

129141
[dc]: deref-coercions.html
142+
[connect]: ../std/net/struct.TcpStream.html#method.connect

0 commit comments

Comments
 (0)