Problems with Postgres crate

I need to access a Postgres database and for that I am trying the Postgres crate ( postgres - Rust). In order to understand syntax I tried the (almost) exact example in the front page of the docs, which goes like this:

use postgres::{Client, NoTls};

fn main(){
        let mut client = Client::connect("host=localhost user=postgres", NoTls)?;
        
        client.batch_execute("
            CREATE TABLE person (
                id      SERIAL PRIMARY KEY,
                name    TEXT NOT NULL,
                data    BYTEA
            )
        ")?;
}

The problem is that won´t compile for me.

The compiler appoints an error in the '?' at the end of 'Client::connect("host=localhost user=postgres", NoTls)?' call.

The whole error message returned by the compiler is:

the `?` operator can only be used in a function that returns `Result` or `Option` (or another type that implements `std::ops::FromResidual`)

cannot use the `?` operator in a function that returns `()`

help: the trait `std::ops::FromResidual<std::result::Result<std::convert::Infallible, postgres::Error>>` is not implemented for `()`rustc(E0277)
main.rs(3, 1): this function should return `Result` or `Option` to accept `?`
main.rs(5, 76): cannot use the `?` operator in a function that returns `()`

But when I hover the mouse in the 'Client::connect()' function I get that it returns a Result instance, exactly what the '?' operator needed.

What have I done wrong?

1 Like

the problem is that the main function does not return Result<T> and ? only works on functions that return Result<T>

1 Like

But the '?' operator isn´t applied to the 'Client::connect()' function (which returns a Result)?

I am confused to what the main function has to do with applying '?' to the connect function...

$expr? basically translates to:

match $expr {
     Ok(x) => x,
     e => return e,
}

if the expression produces an error, then it is returned. which is why the surrounding function should return Result<_, E> where the E should match the type of the expression's error variant

2 Likes

Umm... now I see. What I should do in order to make this example work is using the 'unwrap()' method instead of the '?' operator at the end of the 'connect' function (which just panics in case of error instead of returning the error variant)

Thank you very much @protalker123

1 Like

? is not actually as simple as i explained by the way, it internally uses Try:

1 Like

my pleasure :hugs:

1 Like

Just make your main function return a result.

1 Like

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.