简体   繁体   中英

Why does mutably borrowing fix an expected trait implementation?

I am using rust sqlx and I am getting a connection from my DB pool for my query:

POOL: OnceCell<Pool<Postgres>> = OnceCell::new();

pub async fn get_connection() -> PoolConnection<Postgres> {
    POOL.get().unwrap().acquire().await.unwrap()
}

pub async fn fetch_users() -> Result<Vec<User>> {
    let result = sqlx::query_as!(User,
        r#"SELECT * FROM users"#)
        .fetch_all(get_connection().await).await?;
        Ok(result)
}

But get_connection().await is giving me an error:

the trait bound `sqlx::pool::PoolConnection<sqlx::Postgres>: sqlx::Executor<'_>` is not satisfied expected an implementor of trait `sqlx::Executor<'_>`

The compiler is telling me to fix by using consider mutably borrowing here: `&mut` which works fine when I change to &mut get_connection().await .

I don't understand why this fixes the issue. Can anyone explain?

Looking at the implementations for sqlx::Executor , all of them are on some &mut T type. It is implemented for &mut PoolConnection<Postgres> but not PoolConnection<Postgres> .

Adding &mut changes it from passing a PoolConnection<Postgres> into a &mut PoolConnection<Postgres> . This is required since Rust does not auto-borrow function parameters.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM