提交 dcd470fe 编写于 作者: B bors

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!
......@@ -964,6 +964,14 @@ fn to_socket_addrs(&self) -> io::Result<vec::IntoIter<SocketAddr>> {
}
}
#[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 {
......
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册