diff options
| author | bors <bors@rust-lang.org> | 2020-06-23 00:13:50 +0000 |
|---|---|---|
| committer | bors <bors@rust-lang.org> | 2020-06-23 00:13:50 +0000 |
| commit | dcd470fe1be03136a8e1794b7e2cc6179bbd9d92 (patch) | |
| tree | 5d966e819291a458c6e9b8ebbf49244c1c108092 | |
| parent | cbf356a1a5677b1c073f09ba833d8247c7ed01aa (diff) | |
| parent | 2764e54c29d0f19242e794d5eecd00cc5470f530 (diff) | |
| download | rust-dcd470fe1be03136a8e1794b7e2cc6179bbd9d92.tar.gz rust-dcd470fe1be03136a8e1794b7e2cc6179bbd9d92.zip | |
Auto merge of #73007 - yoshuawuyts:socketaddr-from-string-u16, r=sfackler
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!
| -rw-r--r-- | src/libstd/net/addr.rs | 8 |
1 files changed, 8 insertions, 0 deletions
diff --git a/src/libstd/net/addr.rs b/src/libstd/net/addr.rs index b8fa1a7f744..8c8d1aadf48 100644 --- a/src/libstd/net/addr.rs +++ b/src/libstd/net/addr.rs @@ -964,6 +964,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 { |
