How can I force String to & str for the purpose of using ToSocketAddrs?

When a string is saved as a String rather than &str , it does not implement the ToSocketAddrs . The closest that it does is impl<'a> ToSocketAddrs for (&'a str, u16) .

 use std::net::TcpStream; fn main() { let url = "www.google.com".to_string(); // String let url2 = "www.google.com"; // &'static str let port = 80; // Does not work let tcp = TcpStream::connect((url, port)); // Works let tcp2 = TcpStream::connect((url2, port)); } 

This fails:

 error[E0277]: the trait bound `(std::string::String, {integer}): std::net::ToSocketAddrs` is not satisfied --> src/main.rs:9:11 | 9 | let tcp = TcpStream::connect((url, port)); | ^^^^^^^^^^^^^^^^^^ the trait `std::net::ToSocketAddrs` is not implemented for `(std::string::String, {integer})` | = help: the following implementations were found: <(std::net::Ipv6Addr, u16) as std::net::ToSocketAddrs> <(std::net::Ipv4Addr, u16) as std::net::ToSocketAddrs> <(&'a str, u16) as std::net::ToSocketAddrs> <(std::net::IpAddr, u16) as std::net::ToSocketAddrs> = note: required by `std::net::TcpStream::connect` 

How can I force String to &str to implement the ToSocketAddrs sign? From the documentation for Rust 1.0, I thought String automatically move to &str .

+6
source share
2 answers

The answer to hauleth will work for you, but that is not the whole story. In particular, your String does not force &str , because forced enforcement does not automatically work when matching attributes, like RFC 0401 . Therefore, using a simple &url will not work in this case, because automatic deref will not be applied to it. Instead of getting &str , you just get &String , which does not have a corresponding impl for ToSocketAddrs . However, you can explicitly call deref with the dereference operator. In particular, &*url should work. ( &url[..] also works because [..] is the syntax for โ€œtake snippet over everythingโ€, but it's a bit more verbose.)

+8
source

Since std::net::ToSocketAddrs is only implemented in (&str, _) , you need to take a fragment of the string using the syntax slice &url[..] :

 let tcp = TcpStream::connect((&url[..], port)); 
+4
source

Source: https://habr.com/ru/post/987786/


All Articles