Here is the usage. I want to have a DataSource<dyn Trait> instead of the origin type, but as operator does not work here. Unsafe code is allowed, but I still have no idea. The trait is provided externally, that is to say I don't know what trait the user will coerce to. How can I implement this coercion? Thanks.

use std::cell::RefCell; use std::rc::Rc; pub struct DataSource<T: ?Sized> { current: RefCell<Rc<T>>, } impl<T: ?Sized> DataSource<T> { pub fn new(init: Rc<T>) -> Rc<Self> { Rc::new(Self { current: init.into(), }) } pub fn write(&self, data: Rc<T>) { self.current.replace(data); } } pub struct DataReader<T: ?Sized> { source: Rc<DataSource<T>>, } impl<T: ?Sized> DataReader<T> { pub fn new(source: Rc<DataSource<T>>) -> Self { Self { source } } pub fn read(&self) -> Rc<T> { self.source.current.borrow().clone() } } fn main() { let source: Rc<DataSource<String>> = DataSource::new(Rc::new("abc".to_string())); let reader = DataReader::new(source.clone()); let str_abc = reader.read(); source.write(Rc::new("123".to_string())); let str_123 = reader.read(); assert_eq!(*str_abc, "abc"); assert_eq!(*str_123, "123"); // // how to implement? // let reader_dyn: DataReader<dyn ToString> = reader as _; } 

5 posts - 4 participants

Read full topic