Advertisement
NLinker

Using struct Wrap<E: Trait>(E) with Box

Jul 15th, 2019
455
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Rust 1.41 KB | None | 0 0
  1. // https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=edd0ab90ff3c482b86a21ff9e06277d1
  2.  
  3. mod ext {
  4.     use std::fmt::Debug;
  5.     use std::fmt;
  6.    
  7.     pub trait Trait: Debug {
  8.         fn write_t(&self, _f: &mut fmt::Formatter) -> Result<(), fmt::Error> { Ok(()) }
  9.     }
  10.    
  11.     #[derive(Debug, Clone, Copy)]
  12.     pub struct T0;
  13.     impl Trait for T0 {
  14.         fn write_t(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
  15.             f.write_str("T0")
  16.         }
  17.     }
  18.    
  19.     #[derive(Debug, Clone, Copy)]
  20.     pub struct T1;
  21.     impl Trait for T1 {
  22.         fn write_t(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
  23.             f.write_str("T1")
  24.         }
  25.     }
  26.    
  27.     #[derive(Debug, Clone, Copy)]
  28.     pub struct Wrap<E: Trait>(pub E);
  29. }
  30.  
  31. mod main {
  32.     use crate::ext;
  33.     use std::fmt;
  34.    
  35.     impl<T> ext::Trait for Box<T> where T: ext::Trait + ?Sized {
  36.         fn write_t(&self, _f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
  37.             // self.write_t(f)
  38.             // TODO
  39.             Ok(())
  40.         }
  41.     }
  42.     pub fn test(flag: bool) {
  43.         let b: Box<dyn ext::Trait> = if flag {
  44.             Box::new(ext::T0)
  45.         } else {
  46.             Box::new(ext::T1)
  47.         };
  48.         let w: ext::Wrap<Box<dyn ext::Trait>> = ext::Wrap(b);
  49.         println!("{:?}", w);
  50.     }
  51. }
  52.  
  53. fn main() {
  54.     main::test(false);
  55.     main::test(true);
  56. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement