无法解析带端口的IP地址。

huangapple go评论54阅读模式
英文:

Not able to parse ip address with port

问题

我正在尝试解析这个字符串为 IP 地址

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

这段代码摘自 https://github.com/bluejekyll/trust-dns/tree/main/crates/client#example

我遇到了这个错误

error[E0282]: 需要类型注解
  --> src/main.rs:15:13
   |
15 |         let address = "8.8.8.8:53".parse().unwrap();
   |             ^^^^^^^
   |
help: 考虑为 `address` 添加显式类型注解
   |
15 |         let address: /* Type */ = "8.8.8.8:53".parse().unwrap();
   |                    ++++++++++++

而以下代码段可以正常工作

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

只是想知道 README 是否有误?

英文:

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

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 ?

答案1

得分: 4

README中的代码如下

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

由于 UdpClientConnection::new() 接受一个 std::net::SocketAddr 作为参数,编译器将推断 address 的类型必须解析为这个类型,也就是使用 std::net::SocketAddrFromStr 实现。这就是为什么README可以正常工作。

将你的代码更改为:

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

然后它应该可以工作。


<details>
<summary>英文:</summary>

The code in the README reads as

```rust
let address = &quot;8.8.8.8:53&quot;.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 = &quot;8.8.8.8:53&quot;.parse().unwrap();

and it should work.

huangapple
  • 本文由 发表于 2023年5月30日 05:05:53
  • 转载请务必保留本文链接:https://go.coder-hub.com/76360320.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定