简体   繁体   English

为什么可变借用修复了预期的特征实现?

[英]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:我正在使用 rust sqlx,并且我正在从我的数据库池获取连接以进行查询:

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:但是get_connection().await给了我一个错误:

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 .编译器告诉我通过using consider mutably borrowing here: `&mut`当我更改为&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.查看sqlx::Executor实现,它们都属于某种&mut T类型。 It is implemented for &mut PoolConnection<Postgres> but not PoolConnection<Postgres> .它是为&mut PoolConnection<Postgres>而不是PoolConnection<Postgres>实现的。

Adding &mut changes it from passing a PoolConnection<Postgres> into a &mut PoolConnection<Postgres> .添加&mut会将其从传递PoolConnection<Postgres>更改为&mut PoolConnection<Postgres> This is required since Rust does not auto-borrow function parameters.这是必需的,因为 Rust 不会自动借用 function 参数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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