找不到匹配的类型,expect()找到使用lookup_host时的结果

时间:2015-08-29 10:56:03

标签: rust

我正在使用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

1 个答案:

答案 0 :(得分:18)

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

#![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();
}