jweinst1
4/2/2017 - 12:25 AM

example of using an enum as dynamic typing in Rust

example of using an enum as dynamic typing in Rust

//rust example of dynamic typing with enums

enum Value {
    Int(i32),
    Bool(bool),
    List(Vec<Value>)
}


fn main() {
    let val = Value::Int(1);
    match val {
        Value::Int(num) => println!("Has the number {}", num),
        Value::Bool(b) => println!("Has the bool {}", b),
        Value::List(l) => println!("This is a list")
    }
    let bl = Value::Bool(false);
    match bl {
        Value::Int(num) => println!("Has the number {}", num),
        Value::Bool(b) => println!("Has the bool {}", b),
        Value::List(l) => println!("This is a list")
    }
    let vallist = vec![Value::Int(4), Value::Int(2)];
    let ll = Value::List(vallist);
        match ll {
        Value::Int(num) => println!("Has the number {}", num),
        Value::Bool(b) => println!("Has the bool {}", b),
        Value::List(l) => println!("This is a list")
    }
}

/*Has the number 1
Has the bool false
This is a list*/