简体   繁体   English

为了实现ToSocketAddrs特性,我怎样才能将String强制转换为&str?

[英]How can I coerce a String into a &str for the purposes of implementing the ToSocketAddrs trait?

When a string is stored as a String rather than a &str it fails to implement the trait ToSocketAddrs . 当字符串存储为String而不是&str它无法实现特征ToSocketAddrs The closest possible one that does is impl<'a> ToSocketAddrs for (&'a str, u16) . 最接近的可能是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 with: 这失败了:

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 coerce a String into a &str for the purposes of implementing the ToSocketAddrs trait? 为了实现ToSocketAddrs特性,我怎样才能将String强制转换为&str From the documentation for Rust 1.0, I thought that String would automatically move to &str . 从Rust 1.0的文档中,我认为String会自动移动到&str

hauleth's answer will work for you, but it's not quite the whole story. hauleth的回答对你有用,但并不是全部。 In particular, your String isn't coercing to a &str because auto deref coercion does not kick in when trait matching, as per RFC 0401 . 特别是,你的String不会强制转换为&str ,因为根据RFC 0401 ,当特征匹配时,auto deref强制不会启动。 Therefore, using a plain &url won't work in this case because auto deref won't be applied to it. 因此,在这种情况下使用plain &url将不起作用,因为不会对其应用auto deref。 Instead of getting an &str , you'll just get a &String , which doesn't have a matching impl for ToSocketAddrs . 你不会得到一个&str ,而只是得到一个&String ,它没有ToSocketAddrs的匹配impl。 However, you can explicitly cause deref to happen with the dereference operator. 但是,您可以使用取消引用运算符显式地导致deref。 In particular, &*url should work. 特别是, &*url应该可以工作。 ( &url[..] also works because [..] is the syntax for "take a slice over everything", but it's a bit more verbose.) &url[..]也有效,因为[..]是“对所有内容进行切片”的语法,但它有点冗长。)

由于std::net::ToSocketAddrs仅在(&str, _)上实现(&str, _)您需要使用&url[..]切片语法来获取字符串的一部分:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM