From 49597fcbf26736ac2b2f7d6beab27f42a44bf306 Mon Sep 17 00:00:00 2001 From: Thomas Karpiniec Date: Sun, 24 May 2015 13:54:05 +1000 Subject: [PATCH 1/2] book: explanation that String -> &str coercion doesn't happen for &str traits --- src/doc/trpl/strings.md | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/src/doc/trpl/strings.md b/src/doc/trpl/strings.md index c354fd09edd8..656b9d49126b 100644 --- a/src/doc/trpl/strings.md +++ b/src/doc/trpl/strings.md @@ -49,6 +49,18 @@ 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 +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 +139,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 From 2b3354cbf8cc8eba08cceeda3deb615d6329185f Mon Sep 17 00:00:00 2001 From: Thomas Karpiniec Date: Mon, 25 May 2015 18:38:17 +1000 Subject: [PATCH 2/2] book: add no_run and use statement to strings no-coercion example --- src/doc/trpl/strings.md | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/src/doc/trpl/strings.md b/src/doc/trpl/strings.md index 656b9d49126b..55154036286d 100644 --- a/src/doc/trpl/strings.md +++ b/src/doc/trpl/strings.md @@ -54,7 +54,9 @@ 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 +```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();