[英]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.