DEV Community

BC
BC

Posted on

Day3:structs,enum - 100DayOfRust

Struct

Use struct to build structure, and you can destructure the struct using a let binding:

struct Point(i32, i32);

struct Rect {
    top_left: Point,
    bottom_right: Point,
}

fn rect_area(rect: &Rect) -> i32 {
    // here we used a nested destructuring
    let Rect { top_left: Point(x1, y1),
               bottom_right: Point(x2, y2)} = rect;
    let width = x2 - x1;
    let height = y2 - y1;
    width * height
}

fn main() {
    let rect = Rect {top_left: Point(1, 2),
                     bottom_right: Point(3, 4)};
    let area = rect_area(&rect);
    println!("Area of rect is {}", area);
}
Enter fullscreen mode Exit fullscreen mode

Result:

Area of rect is 4
Enter fullscreen mode Exit fullscreen mode

Enum

enum Operator {
    Add,
    Sub,
    Mul,
    Div,
}

#[allow(dead_code)]
type Op = Operator;


// we can implement methods for enum
impl Operator {
    fn run(&self, i: f32, j: f32) -> f32 {
        match self {
            Operator::Add => i + j,
            Operator::Sub => i - j,
            Operator::Mul => i * j,
            Operator::Div => i / j,   
        }
    }
}

fn main() {
    let adder = Operator::Add;
    let suber = Operator::Sub;
    let muler = Operator::Mul;
    let diver = Operator::Div;
    let num1 = 3 as f32;
    let num2 = 4 as f32;
    println!("{} + {} = {}", num1, num2, adder.run(num1, num2));
    println!("{} - {} = {}", num1, num2, suber.run(num1, num2));
    println!("{} * {} = {}", num1, num2, muler.run(num1, num2));
    println!("{} / {} = {}", num1, num2, diver.run(num1, num2));

}
Enter fullscreen mode Exit fullscreen mode

Result:

3 + 4 = 7
3 - 4 = -1
3 * 4 = 12
3 / 4 = 0.75
Enter fullscreen mode Exit fullscreen mode

Enum can be used as C-like enums

enum Color {
   Red = 0xff0000,
   Green = 0x00ff00,

}
Enter fullscreen mode Exit fullscreen mode

Enum with different type

enum WebEvent {
    PageLoad,
    KeyPress(char),
    Click {x: i64, y: i64},
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)