我用std::net::lookup_host.当我构建时,会发生一个错误.我使用的是Rust 1.2.

use std::net;
fn main() {
    for host in try!(net::lookup_host("rust-lang.org")) {
        println!("found address : {}", try!(host));
    }
}

错误

<std macros>:5:8: 6:42 error: mismatched types:
 expected `()`,
    found `core::result::Result<_, _>`
(expected (),
    found enum `core::result::Result`) [E0308]
<std macros>:5 return $ crate:: result:: Result:: Err (
<std macros>:6 $ crate:: convert:: From:: from ( err ) ) } } )
<std macros>:1:1: 6:48 note: in expansion of try!
exam.rs:4:14: 4:53 note: expansion site
note: in expansion of for loop expansion
exam.rs:4:2: 6:3 note: expansion site
<std macros>:5:8: 6:42 help: run `rustc --explain E0308` to see a detailed explanation
<std macros>:5:8: 6:42 error: mismatched types:
 expected `()`,
    found `core::result::Result<_, _>`
(expected (),
    found enum `core::result::Result`) [E0308]
<std macros>:5 return $ crate:: result:: Result:: Err (
<std macros>:6 $ crate:: convert:: From:: from ( err ) ) } } )
<std macros>:1:1: 6:48 note: in expansion of try!
exam.rs:5:34: 5:44 note: expansion site
note: in expansion of format_args!
<std macros>:2:25: 2:56 note: expansion site
<std macros>:1:1: 2:62 note: in expansion of print!
<std macros>:3:1: 3:54 note: expansion site
<std macros>:1:1: 3:58 note: in expansion of println!
exam.rs:5:3: 5:46 note: expansion site
note: in expansion of for loop expansion
exam.rs:4:2: 6:3 note: expansion site
<std macros>:5:8: 6:42 help: run `rustc --explain E0308` to see a detailed explanation
error: aborting due to 2 previous errors

推荐答案

只能从返回Result的函数中使用try!宏,因为如果表达式是Err,则宏会try 从函数中返回return.

#![feature(lookup_host)]

use std::io::Error;
use std::net;

fn main0() -> Result<(), Error> {
    for host in try!(net::lookup_host("rust-lang.org")) {
        println!("found address : {}", try!(host));
    }
    Ok(())
}

fn main() {
    // unwrap() will panic if main0() returns an error.
    main0().unwrap();
}

Rust相关问答推荐

为什么我们不能通过指针算法将Rust原始指针指向任意地址?'

如何从铁 rust 中呼唤_mm_256_mul_ph?

为什么我不能从带有字符串的 struct 的引用迭代器中收集VEC<;&;str&>?

带扫描的铁 rust 使用滤镜

字段类型为Boxed的 struct 的生存期必须超过static

无符号整数的Rust带符号差

通过RabbitMQ取消铁 rust 中长时间运行的人造丝任务的策略

将Vec<;U8&>转换为Vec<;{Float}&>

不同类型泛型的映射

为什么`tokio::main`可以直接使用而不需要任何导入?

Rust 中的静态引用

在 Rust 中,为什么 10 个字符的字符串的 size_of_val() 返回 24 个字节?

Rust 中多个 & 符号的内存表示

try 从标准输入获取用户名和密码并删除 \r\n

`tokio::pin` 如何改变变量的类型?

如何使用泛型满足 tokio 异步任务中的生命周期界限

Rust 中 `Option` 的内存开销不是常量

你能告诉我如何在 Rust 中使用定时器吗?

预期类型参数,发现不透明类型

如何将 while 循环内的用户输入添加到 Rust 中的向量?