Trying to build a database connection pool using tokio, hyper and postgres

Can someone help me with my code?

I'm struggling to understand how you can work with shared mutable data and tokio.
Currently I'm only having this compile time error:

error[E0515]: cannot return value referencing local data `database`
	--> src/main.rs:42:9
	 |
 41      |         database.query(sql, params)
	 |         --------^^^^^^^^^^^^^^^^^^^
	 |         |
	 |         returns a value referencing data owned by the current function
	 |         `database` is borrowed here
	error: aborting due to previous error
	For more information about this error, try `rustc --explain E0515`.

I tried to work with lifetimes to tell the compiler that the passed data is valid, but I guess I'm misunderstanding the error message.

I'm happy for any major or minor advice!
Thanks in advance.

Ah, I see why you're confused. I assume you're thinking "I moved database into the async block, so what's wrong with using it?"

Well that's not what it's complaining about: The problem is that since you have no semicolon at the end of the line, the return value of the block is whatever query returns — i.e. it's the future representing the contents of the async function query, and this future borrows from database.

Note that tokio::spawn returns a JoinHandle which is a future you can await, and it completes to whatever you return in the spawned task, so by returning it from the async block, the handle (which you immediately drop) would get this value on completion.

If you add the semicolon, you get this warning:

warning: unused implementer of `std::future::Future` that must be used
  --> src/main.rs:41:9
   |
41 |         database.query(sql, params);
   |         ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
   |
   = note: `#[warn(unused_must_use)]` on by default
   = note: futures do nothing unless you `.await` or poll them

Naturally you need to await it to actually run the future (and the query), so throw an await and a semicolon on that query, and you're good to go.

Thanks a lot.
That error message was misleading me.

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.