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

Not able to parse ip address with port

I am trying to parse this string to a ip address

let address = "8.8.8.8:53".parse().unwrap();

This snippet is from https://github.com/bluejekyll/trust-dns/tree/main/crates/client#example

I am getting this 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[E0282]: type annotations needed
  --> src/main.rs:15:13
   |
15 |         let address = "8.8.8.8:53".parse().unwrap();
   |             ^^^^^^^
   |
help: consider giving `address` an explicit type
   |
15 |         let address: /* Type */ = "8.8.8.8:53".parse().unwrap();
   |                    ++++++++++++

While the following snippet works fine

    let address:Ipv4Addr = "8.8.8.8".parse().unwrap();

Just wondering is readme is wrong ?

>Solution :

The code in the README reads as

let address = "8.8.8.8:53".parse().unwrap();
let conn = UdpClientConnection::new(address).unwrap();

Since UdpClientConnection::new() takes a std::net::SocketAddr as it’s argument, the compiler will infer that the type of adress has to resolve to this type, that is, using std::net::SocketAddr‘s implementation of FromStr. This why the README works as is.

Change your code to

use std::net::SocketAddr;
let address: SocketAddr = "8.8.8.8:53".parse().unwrap();

and it should work.

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