英文:
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::SocketAddr
的 FromStr
实现。这就是为什么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 = "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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论