Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Into<SocketAddr> for String

I’m trying to give a String to the warp::server().run() function as the listening address. But I do not know how to impl Into<SocketAddr> for String.

Code

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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`

>Solution :

Conversion from a &str or String into a SocketAddr is fallible, e.g. "" cannot be mapped to a valid SocketAddr.

Thus you need to use a fallible conversion to obtain a type that implements Into<SocketAddr>, one such type is SocketAddr itself. You can convert a &str to a SocketAddr through FromStr or TryFrom which enable you to write "127.0.0.1:3030".parse::<SocketAddr>().unwrap().

Another option is changing the way you pass your address data to the run() method, e.g. ([u8;4], u16) should implement direct conversion since the type constrains it to valid SocketAddrs.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading