• Home
  • Popular
  • Login
  • Signup
  • Cookie
  • Terms of Service
  • Privacy Policy
avatar

Posted by John Dev


08 Jan, 2025

Updated at 20 Jan, 2025

Storing variants

Is there a better easier way to store variants?

use std::any::Any; // 1.0.0

struct A {
    a: Vec<Box<dyn Any>>
}

#[derive(Debug,Clone)]
enum B<T> {
    Anything(T)
}

impl<T> B<T> {
   fn unwrap(self) -> T {
        match self {
            B::Anything(val) => val,
        }
    }
}

#[derive(Debug, Clone)]
struct X{
    x:String
}

#[derive(Debug, Clone)]
struct Y{
    y:String
}

fn main() {
    let v = A {
        a: vec![Box::new(B::Anything(X{x:"data".to_string()})),Box::new(B::Anything(Y{y:"y data".to_string()}))]
    };
    v.a.into_iter().for_each(| i| {
        if i.is::<B<X>>() {
            let x = <B<X> as Clone>::clone(&i.downcast::<B<X>>().as_ref().unwrap()).unwrap().x;
            dbg!(x);
        } else if i.is::<B<Y>>() {
            let y = <B<Y> as Clone>::clone(&i.downcast::<B<Y>>().as_ref().unwrap()).unwrap().y;
            dbg!(y);
        }
    });
}

(Playground)

Errors:

   Compiling playground v0.0.1 (/playground)
    Finished `dev` profile [unoptimized + debuginfo] target(s) in 1.47s
     Running `target/debug/playground`
[src/main.rs:37:13] x = "data"
[src/main.rs:40:13] y = "y data"

2 posts - 1 participant

Read full topic