如何在任何实现了 PgExecutor 的类型上实现一个 trait?

huangapple go评论66阅读模式
英文:

How to implement a trait on any type that implements PgExecutor?

问题

我有自己的特性来扩展`PgExecutor`特性提供的功能。

我想要在任何实现了`PgExecutor`的东西上实现这些特性,但老实说,我遇到了一些困难。

```rust
#[async_trait]
impl<'a, T> PgExecutorExt for T
    where T: PgExecutor<'a> + Sync
{
    async fn my_read_method(&self) -> anyhow::Result<()> {
        sqlx::query_as!(...)
        .fetch_one(self)
        .await?;

        Ok(())
    }
}

但我得到了以下错误:

未满足`&T: Executor<'_>`的特性约束
`Executor<'_>`特性未为`&T`实现

.fetch_one(self)调用上。

有没有人知道发生了什么?谢谢!


<details>
<summary>英文:</summary>

I have my own trait to extend the functionality that the `PgExecutor` trait provides.

I want to implement these trait on anything that implements `PgExecutor` but I&#39;m honestly having a hard time.


```rust
#[async_trait]
impl&lt;&#39;a, T&gt; PgExecutorExt for T
    where T: PgExecutor&lt;&#39;a&gt; + Sync
 {
    async fn my_read_method(&amp;self) -&gt; anyhow::Result&lt;()&gt; {
        sqlx::query_as!(...)
        .fetch_one(self)
        .await?;

        Ok(())
    }
}

But I'm getting the following error:

the trait bound `&amp;T: Executor&lt;&#39;_&gt;` is not satisfied
the trait `Executor&lt;&#39;_&gt;` is not implemented for `&amp;T` 

On the .fetch_one(self) call

anyone has any clue on what is going on??
Thank you!

答案1

得分: 1

Executor::fetch_one() 函数接受 self,而不是 &amp;self。您需要在您的特性定义和此实现中将 &amp;self 更改为 self,这应该会解决问题。

英文:

The Executor::fetch_one() function takes self, not &amp;self. You need to change &amp;self to self in your trait definition and this implementation, and that should fix the issue.

huangapple
  • 本文由 发表于 2023年6月19日 23:42:33
  • 转载请务必保留本文链接:https://go.coder-hub.com/76508173.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定