Using Traits as types in struct gives error

#1

Im trying to get the following code working:

pub trait AccountProvider {
    fn getAccount() -> String;
}

pub struct AccountService<'a> {
    provider: &'a (AccountProvider + 'a),
}

impl<'a> AccountService<'a> {
    pub fn new(provider: &'a AccountProvider) -> AccountService<'a> { 
        AccountService { provider }
    }
}

It have given me lots of problems but after finding this i thought the problem was solved. However I cant get this working since Im getting the following error:

the traitaccount::account_provider::AccountProvidercannot be made into an object

Why am I getting this error and what do I need to change to get this working?

#2

You want to store a reference to an object in AccountService.provider, but the trait has only a “static” getAccount() without &self, so there’s no object involved there. Your trait is not for provider.getAccount(), but only for <SomeType as AccountProvider>::getAccount().

Changing fn getAccount() to fn getAccount(&self) solves the problem.

BTW, a temporary, scope-limited AccountService<'a> might be pain to use and spread lifetime annotations throughout entire codebase. Usually things are stored in structs via Box<dyn AccountProvider> that makes structs self-contained and possible to store permanently.