Impl for trait needs Arc

⚓ rust    📅 2025-07-03    👤 surdeus    👁️ 2      

surdeus

Info

This post is auto-generated from RSS feed The Rust Programming Language Forum - Latest topics. Source: Impl for trait needs Arc

Most of this is reasonably straightforward but my challenge is that I want to implement a trait, but I need self to be in an Arc for the implementation. So, in the code below it's the // I want Arc<Client> here so I can clone it is the important point.

I tried several approaches including implementing the trait for Arc<Client> but that doesn't work. I also had the idea of having Client implement an InnerTrait and then use that inside the Arc for things, but couldn't get that to work either.

Playground link (doesn't work of course but might be easier to work with than code here)

use std::sync::Arc;

struct Client;
struct Other;

impl Other {
    fn run_task(c: Arc<Client>, function) -> Other {
        // spawns a task that runs the function param
    }
}

trait Factory {
    fn func(&self, val: i32) -> Other;
}

// I could impl for Arc<Client> but that causes a problem later
impl Factory for Client {
    fn func(&self, val: i32) -> Other {
        // I want Arc<Client> here so I can clone it
        Other::run_task(self_that_is_in_Arc.clone(), move |c| c.do_stuff());
    }
}

struct X {
    my_factory: Arc<dyn Factory>
}

// I could have `where Arc<T>: Factory` but that causes a problem later
impl X {
    pub fn new(the_factory: Arc<dyn Factory>) -> Self {
        Self {
            my_factory: the_factory
        }
    }
}

pub fn main() {
    let first_client = Arc::new(Client::new());
    X::new(first_client.clone());
}

4 posts - 3 participants

Read full topic

🏷️ rust_feed