Methods of determining why object doesn't match trait?

I have a structure with a generic parameter, there is a method which is supposed to return an object which satisfies the generic parameter.

However I keep getting errors indicating this object does not match the generic parameter:

expected type parameter `T`, found `&mut redis::aio::MultiplexedConnection`
    = note: expected type parameter `T`
            found mutable reference `&mut redis::aio::MultiplexedConnection`
    = help: type parameters must be constrained to match other types
    = note: for more information, visit

Looking at the docs for the object I am returning, I believe it does implement the trait which the generic type parameter specifies.

I have gotten errors like this in the past, and usually I fixed them by realizing that the method signatures of the trait called for something like &mut self which meant I had to return a mutable reference of that object.

This time I tried fixing the error by making sure the trait's method signatures matched what I was returned by to no avail.

Here is a snippet of my code. I am using the Rust Redis library, but I feel like this error is more generally a generic type parameter and traits question.

use redis::aio::{ConnectionLike, MultiplexedConnection};
use redis::Client;

struct Foobar<T: ConnectionLike> {
    client: Client,

impl <T: ConnectionLike> Foobar<T> {
  fn make_connection_like(&mut self) -> T {
    let (mut conn, _driver) = self.client.get_multiplexed_async_connection().await.unwrap();

    &mut conn

Your problem is not that the type you have is missing a trait implementation.
The problem is that your function signature says it returns a generic T, whereas you retrun a concrete type.

The T can be freely chosen by the caller, not by your function.

(Note: you have another issue there in that your T on the defintion of Foobar is unused. Rust will complain about that and not allow it)

Ok gotcha, so instead I should return impl ConnectionLike?

(Yea I reduced my code down a lot, T is used in the struct).

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.