I have a struct having a field which is Arc<Mutex<&mut dyn domthing>> or Mutex<&mut dyn somethin>> according my target. I dont know how can I implement this struct with generic. Any Idea?
how about #[cfg(...)]
s?
Is that the only option?
You can also make your struct generic over T: Borrow<Mutex<…>>
1 Like
would you please give me an example?
use std::{
borrow::Borrow,
fmt::Display,
sync::{Arc, Mutex},
};
struct Sample<T>(T);
impl<'a, T: Borrow<Mutex<&'a dyn Display>>> Sample<T> {
fn print(&self) {
println!("{}", self.0.borrow().lock().unwrap());
}
}
fn main() {
let by_value: Sample<Mutex<&dyn Display>> = Sample(Mutex::new(&"borrow"));
by_value.print();
let arc: Sample<Arc<Mutex<&dyn Display>>> = Sample(Arc::new(Mutex::new(&"arc")));
arc.print();
}
4 Likes
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.