NLinker icon

Associated impl Trait in a box

NLinker | PRO | 07/18/18 01:30:52 PM UTC | 0 ⭐ | 1059 👁️ | Never ⏰ | []
Rust |

1.03 KB

|

None

|

0 👍

/

0 👎

// http://play.rust-lang.org/?gist=89c4e30f6847cd0858cfc49e5b89eb58&version=stable&mode=debug&edition=2015
 
trait ThingValue {
    fn as_string(&self) -> String;
}
 
impl ThingValue for Box<dyn ThingValue> {
    fn as_string(&self) -> String {
        (&*self as &ThingValue).as_string()
    }
}
 
trait Thing {
    type Value: ThingValue;
    fn get_value(&self) -> Self::Value;
}
 
struct SuchValue;
impl ThingValue for SuchValue {
    fn as_string(&self) -> String {
        String::from("qwerty")
    }
}
 
struct Such;
impl Thing for Such {
    type Value = SuchValue;
    fn get_value(&self) -> Self::Value { SuchValue {} }
}
 
struct Wrap<V:ThingValue + 'static, T: Thing<Value = V>> (T);
 
impl<V:ThingValue + 'static, T: Thing<Value = V>> Thing for Wrap<V, T> {
    type Value = Box<dyn ThingValue>;
    fn get_value(&self) -> Box<dyn ThingValue> {
        Box::new(self.0.get_value())
    }
    
}
 
fn main() {
    let things: Vec<Box<dyn Thing<Value = Box<dyn ThingValue>>>> = vec![Box::new(Wrap(Such{}))];
}

Comments