File tree Expand file tree Collapse file tree 1 file changed +13
-0
lines changed Expand file tree Collapse file tree 1 file changed +13
-0
lines changed Original file line number Diff line number Diff 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+
5264Viewing 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
127139feature called ‘[ ` Deref ` coercions] [ dc ] ’.
128140
129141[ dc ] : deref-coercions.html
142+ [ connect ] : ../std/net/struct.TcpStream.html#method.connect
You can’t perform that action at this time.
0 commit comments