[英]Why does moving a function to a default trait method introduce a borrowing error?
[英]Why does mutably borrowing fix an expected trait implementation?
我正在使用 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)
}
但是get_connection().await
给了我一个错误:
the trait bound `sqlx::pool::PoolConnection<sqlx::Postgres>: sqlx::Executor<'_>` is not satisfied expected an implementor of trait `sqlx::Executor<'_>`
编译器告诉我通过using consider mutably borrowing here: `&mut`
当我更改为&mut get_connection().await
时效果很好。
我不明白为什么这可以解决问题。 谁能解释一下?
查看sqlx::Executor
的实现,它们都属于某种&mut T
类型。 它是为&mut PoolConnection<Postgres>
而不是PoolConnection<Postgres>
实现的。
添加&mut
会将其从传递PoolConnection<Postgres>
更改为&mut PoolConnection<Postgres>
。 这是必需的,因为 Rust 不会自动借用 function 参数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.