Type mismatch using traits

Hi,
This is my first post on this forum and I'm pretty new to Rust.
I wrote this code and compiler says:

mismatched types
expected struct Arc<T>
found struct `Arc<UserService<JwtTokenHandler, UserModel>>

here's the code:

pub struct Container<T>
where
    T: IUserService,
{
    user_service: Arc<T>,
}

impl<T> Container<T>
where
    T: IUserService,
{
    fn new() -> Self {
        let user_repository = UserModel::new();
        let jwt_token_handler = JwtTokenHandler::new("secret");

        let user_service = Arc::new(UserService::new(jwt_token_handler, user_repository));

        Self { user_service }
    }
}

How can I fix this ?

impl Container<UserService<JwtTokenHandler, UserModel>> {
    fn new() -> Self {
        let user_repository = UserModel::new();
        let jwt_token_handler = JwtTokenHandler::new("secret");

        let user_service = Arc::new(UserService::new(jwt_token_handler, user_repository));

        Self { user_service }
    }
}
impl<T> Container<T>
where
    T: IUserService,
{
    fn new() -> Self

Means new will return a generic Container<T>, but you are actually returning a specific Container<UserService<JwtTokenHandler, UserModel>>

If you're trying to keep things generic, you need to give the trait a way to construct values of that type

pub trait IUserService {
    fn new(argument: &str) -> Self;
}

pub struct UserService(JwtTokenHandler, UserModel);

impl UserService {
    pub fn new(jwt: JwtTokenHandler, model: UserModel) -> Self {
        Self(jwt, model)
    }
}

impl IUserService for UserService {
    fn new(argument: &str) -> Self {
        let user_repository = UserModel::new();
        let jwt_token_handler = JwtTokenHandler::new(argument);

        UserService::new(jwt_token_handler, user_repository)
    }
}

pub struct Container<T>
where
    T: IUserService,
{
    user_service: Arc<T>,
}

impl<T> Container<T>
where
    T: IUserService,
{
    fn new() -> Self {
        let user_service = Arc::new(T::new("secret"));

        Self { user_service }
    }
}

It's a bit more complicated for a generic UserService of course.

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.