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.