Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mismatched types, expected () found Result when using lookup_host [duplicate]

Tags:

rust

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
like image 761
KoMoRi HiKi Avatar asked Aug 29 '15 10:08

KoMoRi HiKi


1 Answers

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();
}
like image 182
Francis Gagné Avatar answered Oct 04 '22 16:10

Francis Gagné