Advertisement
NLinker

Associated impl Trait in a box

Jul 18th, 2018
442
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Rust 1.03 KB | None | 0 0
  1. // http://play.rust-lang.org/?gist=89c4e30f6847cd0858cfc49e5b89eb58&version=stable&mode=debug&edition=2015
  2.  
  3. trait ThingValue {
  4.     fn as_string(&self) -> String;
  5. }
  6.  
  7. impl ThingValue for Box<dyn ThingValue> {
  8.     fn as_string(&self) -> String {
  9.         (&*self as &ThingValue).as_string()
  10.     }
  11. }
  12.  
  13. trait Thing {
  14.     type Value: ThingValue;
  15.     fn get_value(&self) -> Self::Value;
  16. }
  17.  
  18. struct SuchValue;
  19. impl ThingValue for SuchValue {
  20.     fn as_string(&self) -> String {
  21.         String::from("qwerty")
  22.     }
  23. }
  24.  
  25. struct Such;
  26. impl Thing for Such {
  27.     type Value = SuchValue;
  28.     fn get_value(&self) -> Self::Value { SuchValue {} }
  29. }
  30.  
  31. struct Wrap<V:ThingValue + 'static, T: Thing<Value = V>> (T);
  32.  
  33. impl<V:ThingValue + 'static, T: Thing<Value = V>> Thing for Wrap<V, T> {
  34.     type Value = Box<dyn ThingValue>;
  35.     fn get_value(&self) -> Box<dyn ThingValue> {
  36.         Box::new(self.0.get_value())
  37.     }
  38.    
  39. }
  40.  
  41. fn main() {
  42.     let things: Vec<Box<dyn Thing<Value = Box<dyn ThingValue>>>> = vec![Box::new(Wrap(Such{}))];
  43. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement