11

I am using std::net::lookup_host. When I build, an error occurs. I am using Rust 1.2.

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

Error

<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
Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
KoMoRi HiKi
  • 121
  • 1
  • 4
  • This was [cross-posted to Reddit](https://www.reddit.com/r/rust/comments/3itr2s/how_method_of_use_to_lookup_host_in_stdnet/) – Shepmaster Aug 29 '15 at 13:59

1 Answers1

18

You can only use the try! macro from a function that returns a Result, because the macro tries to return from the function if the expression is an 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();
}
Francis Gagné
  • 60,274
  • 7
  • 180
  • 155