Skip to content

Commit 8954652

Browse files
authored
Rollup merge of rust-lang#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!
2 parents 9aa792e + 2764e54 commit 8954652

File tree

1 file changed

+8
-0
lines changed

1 file changed

+8
-0
lines changed

src/libstd/net/addr.rs

+8
Original file line numberDiff line numberDiff line change
@@ -1000,6 +1000,14 @@ impl ToSocketAddrs for (&str, u16) {
10001000
}
10011001
}
10021002

1003+
#[stable(feature = "string_u16_to_socket_addrs", since = "1.46.0")]
1004+
impl ToSocketAddrs for (String, u16) {
1005+
type Iter = vec::IntoIter<SocketAddr>;
1006+
fn to_socket_addrs(&self) -> io::Result<vec::IntoIter<SocketAddr>> {
1007+
(&*self.0, self.1).to_socket_addrs()
1008+
}
1009+
}
1010+
10031011
// accepts strings like 'localhost:12345'
10041012
#[stable(feature = "rust1", since = "1.0.0")]
10051013
impl ToSocketAddrs for str {

0 commit comments

Comments
 (0)