about summary refs log tree commit diff
diff options
context:
space:
mode:
authorbors <bors@rust-lang.org>2015-05-25 18:18:11 +0000
committerbors <bors@rust-lang.org>2015-05-25 18:18:11 +0000
commit6770253c67979012295a2e6ec8be18567ac674f7 (patch)
tree8e4e8217292fe6c34e3308a0d438a72a95329b35
parent45001c0ef8a9a09f93e65d2d4d8d64364bb7d9ba (diff)
parent2b3354cbf8cc8eba08cceeda3deb615d6329185f (diff)
downloadrust-6770253c67979012295a2e6ec8be18567ac674f7.tar.gz
rust-6770253c67979012295a2e6ec8be18567ac674f7.zip
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.
-rw-r--r--src/doc/trpl/strings.md15
1 files changed, 15 insertions, 0 deletions
diff --git a/src/doc/trpl/strings.md b/src/doc/trpl/strings.md
index c354fd09edd..55154036286 100644
--- a/src/doc/trpl/strings.md
+++ b/src/doc/trpl/strings.md
@@ -49,6 +49,20 @@ fn main() {
 }
 ```
 
+This coercion does not happen for functions that accept one of `&str`’s traits
+instead of `&str`. For example, [`TcpStream::connect`][connect] has a parameter
+of type `ToSocketAddrs`. A `&str` is okay but a `String` must be explicitly
+converted using `&*`.
+
+```rust,no_run
+use std::net::TcpStream;
+
+TcpStream::connect("192.168.0.1:3000"); // &str parameter
+
+let addr_string = "192.168.0.1:3000".to_string();
+TcpStream::connect(&*addr_string); // convert addr_string to &str
+```
+
 Viewing a `String` as a `&str` is cheap, but converting the `&str` to a
 `String` involves allocating memory. No reason to do that unless you have to!
 
@@ -127,3 +141,4 @@ This is because `&String` can automatically coerce to a `&str`. This is a
 feature called ‘[`Deref` coercions][dc]’.
 
 [dc]: deref-coercions.html
+[connect]: ../std/net/struct.TcpStream.html#method.connect