Proteusiq / hadithi

🧪 Data Science | ⚒️ MLOps | ⚙️ DataOps : Talks about 🦄
15 stars 1 forks source link

Understanding Rust #36

Open Proteusiq opened 1 year ago

Proteusiq commented 1 year ago

struct Pistol {
    kind: String,
    country: String,
    capacity: u8,
    weight: f32, // in kg
}

enum Weapon {
    Beretta(Pistol), // kind 418 by Italian  8 (7+1) rounds weigh 0.31 kg
    Walther(Pistol), //       PPK by German pistol 8 rounds weigh 0.59 kg
}

#[derive(Debug)]
struct Agent {
    name: String,
    target: u8,
    active: bool,
}

impl Agent {
    fn report(&self, extra: u8) -> String {
        let target = if self.active {
            self.target + extra
        } else {
            self.target
        };

        format!(
            "Hello, {name}! You got {target} targets to elimate.",
            name = self.name,
            target = target
        )
    }

    fn weapon(&self, weapon: Weapon) -> String {
        match weapon {
            Weapon::Beretta(p) => format!("{name} selected Beretta {pistol}. Made in {country}, weigh {weight} kg., with {capacity} rounds."
                                        ,name=self.name, pistol=p.kind, country=p.country, weight=p.weight, capacity=p.capacity),
            Weapon::Walther(p) => format!("Oh, that is a {country} made Walter {pistol}, Agent {name}! It weighs {weight} and has {capacity} rounds."
                                        ,name=self.name, pistol=p.kind, country=p.country, weight=p.weight, capacity=p.capacity
            ),
        }
    }
}

fn main() {
    let agent = Agent {
        name: String::from("James Bond"),
        target: 7,
        active: true,
    };
    println!("{:?}", agent.report(2));

    let beratta = Weapon::Beretta(Pistol {
        kind: String::from("418"),
        country: String::from("Italy"),
        capacity: 8,
        weight: 0.31,
    });

    let walther = Weapon::Walther(Pistol {
        kind: "PPK".to_string(),
        country: "Germany".to_string(),
        capacity: 8,
        weight: 0.59,
    });

    for pistol in [beratta, walther] {
        println!("{}", agent.weapon(pistol))
    }
}
Proteusiq commented 1 year ago
use std::fmt::{Display, Formatter, Result};

#[derive(Debug)]
struct Complex {
    real: f32,
    imag: f32,

}

impl Display for Complex {
    fn fmt(&self, f: &mut Formatter) -> Result {
        write!(f, "{real} + {imag}i", real=self.real, imag=self.imag)
    }

}

fn main() {

    let complex = Complex { real: 4.2, imag: 6.7 };
    println!("equation:\n {}", complex);
    println!("\n {:#?}", complex);

}