Skip to content

Commit 6770253

Browse files
committed
Auto merge of #25742 - thombles:tk/StringCoercion, r=steveklabnik
A few of us [over on the forum](https://users.rust-lang.org/t/string-type-coercion-in-rust/1439) have been tripped up by this distinction, which I don't think is mentioned. It's kind of logical if you read the "Deref coercions" page and squint a bit but I think it would be nice to explain it directly. Here's one way we could clarify it.
2 parents 45001c0 + 2b3354c commit 6770253

File tree

1 file changed

+15
-0
lines changed

1 file changed

+15
-0
lines changed

src/doc/trpl/strings.md

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -49,6 +49,20 @@ 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,no_run
58+
use std::net::TcpStream;
59+
60+
TcpStream::connect("192.168.0.1:3000"); // &str parameter
61+
62+
let addr_string = "192.168.0.1:3000".to_string();
63+
TcpStream::connect(&*addr_string); // convert addr_string to &str
64+
```
65+
5266
Viewing a `String` as a `&str` is cheap, but converting the `&str` to a
5367
`String` involves allocating memory. No reason to do that unless you have to!
5468

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

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

0 commit comments

Comments
 (0)