Last active
March 24, 2022 10:52
-
-
Save monadplus/eed98f41738abc3284a152893649cc69 to your computer and use it in GitHub Desktop.
Rust: trait object with existential associated type
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=c7d98a91435963f2cc8568b7dfd04366 | |
| use std::fmt::Debug; | |
| trait MyTrait { | |
| type R: Debug; | |
| fn get_r(&self) -> Box<Self::R>; | |
| } | |
| #[derive(Debug)] | |
| struct A; | |
| impl MyTrait for A { | |
| type R = u32; | |
| fn get_r(&self) -> Box<Self::R> { | |
| Box::new(u32::default()) | |
| } | |
| } | |
| #[derive(Debug)] | |
| struct B; | |
| impl MyTrait for B { | |
| type R = char; | |
| fn get_r(&self) -> Box<Self::R> { | |
| Box::new(char::default()) | |
| } | |
| } | |
| struct AnyVecMyTrait<'a, D: Debug + 'a> { | |
| any_vec: Vec<&'a dyn MyTrait<R = D>> | |
| } | |
| impl<'a, D: Debug> AnyVecMyTrait<'a, D> { | |
| pub fn add<T: MyTrait<R = D>>(&mut self, a: &'a T) { | |
| self.any_vec.push(a); | |
| } | |
| pub fn debug_vec(self) { | |
| for v in self.any_vec.into_iter() { | |
| println!("{:?}", v.get_r()); | |
| } | |
| } | |
| } | |
| #[test] | |
| fn test_vec_of_dyn_object_with_associated_types() { | |
| let a = A; | |
| let b = B; | |
| let mut any_vec = AnyVecMyTrait { | |
| any_vec: vec!(), | |
| }; | |
| any_vec.add(&a); | |
| any_vec.add(&b); // ERROR | |
| any_vec.debug_vec(); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment