Into<SocketAddr> for String

Into<SocketAddr> for String

我正在尝试给 warp::server().run() 函数一个 String 作为监听地址。但我不知道如何为 String.

实现 Into<SocketAddr>

代码

use warp::Filter;

#[tokio::main]
async fn main() {
    // GET /hello/warp => 200 OK with body "Hello, warp!"
    let hello = warp::path!("hello" / String)
        .map(|name| format!("Hello, {}!", name));

    warp::serve(hello)
        .run("127.0.0.1:3030")
        .await;
}

错误

error[E0277]: the trait bound `std::net::SocketAddr: From<&str>` is not satisfied
  --> src/server/mod.rs:24:29
   |
24 |         warp::serve(routes).run("127.0.0.1:3030").await;
   |                             ^^^ the trait `From<&str>` is not implemented for `std::net::SocketAddr`
   |
   = help: the following implementations were found:
             <std::net::SocketAddr as From<(I, u16)>>
             <std::net::SocketAddr as From<SocketAddrV4>>
             <std::net::SocketAddr as From<SocketAddrV6>>
   = note: required because of the requirements on the impl of `Into<std::net::SocketAddr>` for `&str`

&strString 转换为 SocketAddr 是容易出错的,例如"" 无法映射到有效的 SocketAddr

因此您需要使用易出错的转换来获得实现 Into<SocketAddr> 的类型,其中一个类型是 SocketAddr 本身。您可以通过 FromStrTryFrom&str 转换为 SocketAddr,这样您就可以编写 "127.0.0.1:3030".parse::<SocketAddr>().unwrap().

另一种选择是更改将地址数据传递给 run() 方法的方式,例如([u8;4], u16) 应该实施直接转换,因为类型将其限制为有效的 SocketAddrs。