Need help to understand borrowing error


I made an example of integration testing for Hyper with helper function which run a server and execute a test, which passed as parameter.

async fn with_server<T, R>(f: T) -> Result<(), AppError>
    T: Fn(SocketAddr) -> R,
    R: Future<Output = Result<(), AppError>>,

async fn ok_test() -> Result<(), AppError> {
    with_server(|server_addr| async {
        let client = Client::new();
        let uri = format!("http://{}/", server_addr).parse().unwrap();

        let resp = client.get(uri).await?;
        assert_eq!(StatusCode::OK, resp.status());


But i got an error about borrowing:

error[E0515]: cannot return value referencing function parameter `server_addr`
  --> tests/
35 |       with_server(|server_addr| async {
   |  _______________________________^
36 | |         let client = Client::new();
37 | |         let uri = format!("http://{}/", server_addr).parse().unwrap();
   | |                                         ----------- `server_addr` is borrowed here
38 | |
...  |
42 | |         Ok(())
43 | |     })
   | |_____^ returns a value referencing data owned by the current function

Could anybody help me to understand where is a problem? I don't return any value from this test function. Or i'm return a value?

There is a full example

|server_addr| async { ... } returns an anonymous type generated by the async block, which implements the Future trait.

Async blocks borrow variables by default. You might be able to fix the borrow error by changing it to an async move block.

1 Like

Thank you very much! I did not guess to try to place after async.

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