[solved] Returning a struct with reference to trait


#1

Hey there,
I want to abstract away some functionality and return an object that encapsulates methods.
For this I have a struct Client that is meant to hold a reference to its parent:

    pub struct Client<'a, P:'a + HasClient + ?Sized> {
        inner: &'a P,
    }

and a trait at I want to implement for this parent:

    pub trait HasClient: ProvidesData {

        ///Returns the content of `/client/email`
        fn client<'a, P:HasClient+ ?Sized>(&'a self) -> Client<'a, P> {
            Client { // line 101
                inner: self
            }
        }
//...

Could you tell me how to do this correctly? because I keep getting ambiguous errors:

   --> src/project/spec.rs:101:13
    |
101 |             Client {
    |             ^ expected type parameter, found Self
    |
    = note: expected type `project::spec::client::Client<'a, P>`
    = note:    found type `project::spec::client::Client<'_, Self>`

thank you


#2

You’ll have to define the method differently:

fn client(&self) -> Client<Self>

#3

With P as a type parameter on the function, the implementation is required to create a Client<P> for any P that the caller chooses, e.g. <Foo as HasClient>::client::<Bar>(&foo) is a valid UFCS call if Foo and Bar both implement HasClient.

You only know how to make it with self, which is why Client<Self> is a better return type.


#4

I’ve never even seen something like Client<Self>
thank you, this worked immediately