카테고리 없음

Easy Rust in Korean - source code

개발자_이훈규 2022. 9. 7. 16:59
struct Animal {
    name: String
}

trait Canine {
    fn bark(&self) {
        println!("bark");
    }
    
    fn run(&self) {
        println!("run");
    }
}

impl Canine for Animal {
    fn bark(&self) {
        println!("멍멍 {}", self.name);
    }
}

fn main() {
    let my_animal = Animal {
        name: "Mr. Lee".to_string()
    };
    
    my_animal.bark();
    my_animal.run();
}

 

061 trait

// https://doc.rust-lang.org/std/fmt/trait.Display.html
use std::fmt;

#[derive(Debug)]
struct Cat {
    name: String,
    age: u8
}

impl fmt::Display for Cat {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let name = &self.name;
        let age = self.age;
        write!(f, "my cat's name is {} and it is  {} years old", name, age)
    }
}

fn main() {
    let mr_mantle = Cat {
        name: "lee".to_string(),
        age: 4
    };
    
    //println!("this is car : {mr_mantle:?}");
    //println!("this is car : {:?}", mr_mantle);
    println!("{mr_mantle}");
}

 

63 trait

use std::fmt::Debug;

#[derive(Debug)]
struct Monster {
    health: i32
}

#[derive(Debug)]
struct Wizard {
    health: i32
}
#[derive(Debug)]
struct Ranger{
    health: i32
}

trait Magic {}
trait FightClose {}
trait FightFromDistance {}

impl Magic for Wizard {}
impl FightClose for Wizard {}
impl FightClose for Ranger {}
impl FightFromDistance for Ranger {}
impl FightFromDistance for Wizard {}

fn attack_with_bow<T>(character: &T, opponent: &mut Monster, distance: u32) 
where T: FightFromDistance + Debug,
{
    if distance < 10 {
        opponent.health -= 10;
        println!("opponent {} health left", opponent.health);
    }
}

fn attack_with_sword<T>(character: &T, opponent: &mut Monster) 
where T: FightClose + Debug,
{
    opponent.health -= 10;
    println!("opponent {} health left", opponent.health);
}

fn fireball<T>(character: &T, opponent: &mut Monster, distance: u32) 
where T: Magic + Debug,
{
    if distance < 15 {
        opponent.health -= 20;
        println!("opponent {} health left", opponent.health);
    }
}

fn main() {
    let radagast = Wizard {
        health: 60
    };
    let aragorn = Ranger {
        health: 80
    };
    
    let mut uruk_hai = Monster { health: 40 };
    
    attack_with_sword(&radagast, &mut uruk_hai);
    attack_with_bow(&aragorn, &mut uruk_hai, 7);
    fireball(&radagast, &mut uruk_hai, 12);
}

 

64