Rust

[Rust lang] 94. add trait

밍글링글링 2023. 3. 30.
728x90
use std::ops:Add;

#[derive(Debug)]
struct Country {
    name: String,
    population: u32,
    gdp: u32
}

impl Country {
    fn new(name: &str, population: u32, gdp: u32) -> Self {
        Self {
            name: name.to_string(),
            population,
            gdp
        }
    }
}

impl Add for Point {
    type Output = Self;

    fn add(self, other: Self) -> Self {
        Self {
            x: self.x + other.x,
            y: self.y + other.y,
            name: format!("{} and {}", self.name, other.name),
            population: self.population + other.population,
            gdp: self.gdp + other.gdp
        }
    }
}

fn main() {
    let nauru = Country::new("Nauru", 10_670, 160_000_000);
    let vanuatu = Country::new("vanuatu", 307_815, 820_000_000);
    let micronesia = Country::new("micronesia", 104_468, 367_000_000);

    println!("Nauru + Vanuatu + Micronesia = {:?}", nauru + vanuatu + Micronesia);
}
#[derive(Debug)]
struct Character {
    name: String,
    age: u8,
    height: u32,
    weight: u32,
    lifestate: LifeState
}

#[derive(Debug)]
enum LifeState {
    Alive,
    Dead,
    NeverAlive,
    Uncertain
}

impl Character {
    fn new(name: String, age: u8, height: u32, weight: u32, alive:bool) -> {
        Self {
            name,
            age,
            height,
            weight,
            lifestate: if alive {
                LifeState::Alive
            } else {
                LifeState::Dead
            }
        }
    } 
}

impl Default for Character {
    fn default() -> Self {
        Self {
            name: "Billy".to_string(),
            age: 15,
            height: 170,
            weight: 70,
            lifestate: LifeState::Alive
        }
    }
}

fn main() {
    let npc_1 = Character::default();
    println!("{npc_1:?}");
}
728x90

'Rust' 카테고리의 다른 글

[Rust lang] 96. test-driven development  (0) 2023.03.31
[Rust lang] 95. builder pattern  (0) 2023.03.30
[Rust lang] 93. deref trait  (0) 2023.03.30
[Rust lang] 92. attribute part  (0) 2023.03.30
[Rust lang] 91. about impl trait  (0) 2023.03.30

댓글