Tuesday, August 20, 2019

One of powerful usage of Enum in Rust - Part1

Welcome file

Rust programming - Enum inside Struct

You might have come across this scenario in programming where you want to restrict a field type to restricted custom types.

Especially when you are working with APIs, the some of the field types can be one of the multiple custom types. You don’t want to accept the types other than defined custom types. enum can help you in these scenarios.
,eg event types can be ‘pullevent’, 'pushevent", ‘keypress’,‘mouseevvent’ etc

Example progarm

#[derive(Debug)]
///enum defined for vechicle type field
enum Oneoftwo{
    Car(String),
    Bus(String),
   
}
///struct defined for vehicle.
///Here we are using the defined enum as a type for a field in the struct
struct Vehicle{
    type1:Oneoftwo,
    price:i32,
}
///implementation for the vechile to create new instances
impl Vehicle {
    fn new(type1:Oneoftwo,price:i32) -> Vehicle{
        Vehicle{
            type1,
            price,
        }
    }
}

///main program to demostrate how to use enum inside a struct
fn main() {
    ///creating instances of the struct object
    let honda = Vehicle::new(Oneoftwo::Car("honda".to_string()),4000);
    let tata = Vehicle::new(Oneoftwo::Bus("Tata".to_string()),10000);
     
    println!("{:?},{:?}",honda.type1,honda.price);
    println!("{:?},{:?}",tata.type1,tata.price);
}


output:
Car("honda"),4000
Bus("Tata"),10000

No comments: