Skip to content

Commit

Permalink
Rollup merge of #73007 - yoshuawuyts:socketaddr-from-string-u16, r=sf…
Browse files Browse the repository at this point in the history
…ackler

impl ToSocketAddrs for (String, u16)

This adds a convenience impl of `ToSocketAddrs for (String, u16)`. When authoring HTTP services it's common to take command line options for `host` and `port` and parse them into `String` and `u16` respectively. Consider the following program:
```rust
#[derive(Debug, StructOpt)]
struct Config {
    host: String,
    port: u16,
}

async fn main() -> io::Result<()> {
    let config = Config::from_args();
    let stream = TcpStream::connect((&*config.host, config.port))?; // &* is not ideal
    // ...
}
```

Networking is a pretty common starting point for people new to Rust, and seeing `&*` in basic examples can be confusing. Even as someone that has experience with networking in Rust I tend to forget that `String` can't be passed directly there. Instead with this patch we can omit the `&*` conversion and pass `host` directly:
```rust
#[derive(Debug, StructOpt)]
struct Config {
    host: String,
    port: u16,
}

async fn main() -> io::Result<()> {
    let config = Config::from_args();
    let stream = TcpStream::connect((config.host, config.port))?; // no more conversions!
    // ...
}
```

I think should be an easy and small ergonomics improvement for networking. Thanks!
  • Loading branch information
Dylan-DPC authored Jun 5, 2020
2 parents 52ae51b + 2764e54 commit e7c8742
Showing 1 changed file with 8 additions and 0 deletions.
8 changes: 8 additions & 0 deletions src/libstd/net/addr.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1000,6 +1000,14 @@ impl ToSocketAddrs for (&str, u16) {
}
}

#[stable(feature = "string_u16_to_socket_addrs", since = "1.46.0")]
impl ToSocketAddrs for (String, u16) {
type Iter = vec::IntoIter<SocketAddr>;
fn to_socket_addrs(&self) -> io::Result<vec::IntoIter<SocketAddr>> {
(&*self.0, self.1).to_socket_addrs()
}
}

// accepts strings like 'localhost:12345'
#[stable(feature = "rust1", since = "1.0.0")]
impl ToSocketAddrs for str {
Expand Down

0 comments on commit e7c8742

Please sign in to comment.