Closure Trait object

Hi,

Could you help me about can I use trait object in closure?

So when I have this:

struct Data<T> {
  data: T
}

impl<T> Data<T> {
  pub fn update<F, R>(&self, mut f: F) -> R
    where
        F: FnMut(&mut T) -> R,
    {
        f(&mut self.data)
    }
}

If I use a trait called Demo, can i use this trait as a trait object using my Update function? This would help meg with auto completion, as Visual Studio Code somehow does not do auto completion for anonimus closure - even when it knows the exact type I use inside it. When I use type annotation it works well; but inside my project I would not use exact type annotations in my function signatures as types can vary quickly, so I build my project up on traits.

So If I have a trait like:

pub trait Demo {
 fn set_name(&mut self, to: &str);
}

pub struct User {
  name: String,
}

impl Demo for User {
 fn set_name(&mut self, to: &str) {
   self.data = to.to_owned();
 }
}

let mut user = Data { data: User { name: "Demo".to_owned(), } }
user.update(|u: impl Demo| u.set_name("My new name"));

The demo above does not compile, as somehow I cannot use trait object.

Any idea?
For closure auto completion it would be very useful.

Thank you in advance.

Well, first of all impl Trait is not a trait object, second, wanting a trait object there doesn't really work/make sense, since 1. there's always a single concrete type (which lacks any trait bounds) because of the way Data::update() is defined, and 2. closures can't (yet) be generic.

Your code also contains numerous syntax and semantic errors (e.g. with regards to mutability) as well as – I assume – typos, but after fixing them and removing the erroneous type annotation, the following code compiles and runs.

2 Likes