Mehdi
Mehdi

Reputation: 813

Why does the following not compile when trying to connect to Postgres in Rust

When trying to connect to Postgres the following line works as in the docs

let conn = PostgresConnection::connect("postgres://postgres@localhost",
                                       &NoSsl).unwrap();

But once I change that to this:

let conn = try!(PostgresConnection::connect("postgres://postgres@localhost", &NoSsl));

I get the following compile error:

<std macros>:2:59: 2:65 error: mismatched types: expected `()` but found `core::result::Result<<generic #16>,postgres::error::PostgresConnectError>` (expected () but found enum core::result::Result)
<std macros>:2     ($e:expr) => (match $e { Ok(e) => e, Err(e) => return Err(e) })

Upvotes: 0

Views: 224

Answers (1)

Vladimir Matveev
Vladimir Matveev

Reputation: 128081

try!() macro transforms this code:

let conn = try!(PostgresConnection::connect("postgres://postgres@localhost", &NoSsl));

into this:

let conn = match PostgresConnection::connect("postgres://postgres@localhost", &NoSsl) {
    Ok(e) => e,
    Err(e) => return Err(e)
};

That is, in case of error it returns from the function it is invoked in. Hence, this function must return something of type Result<..., PostgresConnectError>. However, in your case it seems that the function you're calling this macro in does not return anything (that is, it returns unit (): fn whatever() { } - no return type).

Result::unwrap(), on the other hand, causes task failure if the result value is Err, and it is a function, so it doesn't depend on function return type.

Upvotes: 3

Related Questions