mirror of
https://github.com/rust-lang/rust
synced 2024-09-15 22:50:55 +00:00
book: explanation that String -> &str coercion doesn't happen for &str traits
This commit is contained in:
parent
38a97becdf
commit
49597fcbf2
|
@ -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
|
||||
|
|
Loading…
Reference in a new issue