본문 바로가기
Rust

[Rust] 고급 Trait 예제 (46일차)

by 꾸압 2023. 1. 29.

 

<예제 코드_1>

impl Iterator for Counter {
    type Item = u32;
    fn next(&mut self) -> Option<Self::Item>;
}

pub trait Iterator<T> {
    fn next(&mut self) -> Option<T>;
}

 


 

<예제 코드_2>

use std::ops::Add;

#[derive(Debug, PartialEq)]
struct Point {
    x: i32,
    y: i32,
}

impl Add for Point {
    type Output = Point;

    fn add(self, other: Point) -> Point {
        Point {
            x: self.x + other.x,
            y: self.y + other.y,
        }
    }
}

fn main() {
    assert_eq!(Point { x: 1, y: 0 } + Point { x: 2, y: 3 },
               Point { x: 3, y: 3 });
}

 


 

<예제 코드_3>

use std::ops::{Add, Sub};

#[derive(Debug, Copy, Clone, PartialEq)]
struct Point {
    x: i32,
    y: i32,
}

impl Add for Point {
    type Output = Self;

    fn add(self, other: Self) -> Self {
        Self {x: self.x + other.x, y: self.y + other.y}
    }
}

impl Sub for Point {
    type Output = Self;

    fn sub(self, other: Self) -> Self {
        Self {x: self.x - other.x, y: self.y - other.y}
    }
}

fn main() {
    assert_eq!(Point {x: 3, y: 3}, Point {x: 1, y: 0} + Point {x: 2, y: 3});
    assert_eq!(Point {x: -1, y: -3}, Point {x: 1, y: 0} - Point {x: 2, y: 3});
}

 


 

<예제 코드_4>

fn main() {
    fn call_with_one<F>(func: F) -> usize
        where F: Fn(usize) -> usize
    {
        func(1)
    }

    let double = |x| x * 2;
    assert_eq!(call_with_one(double), 2);
}

 


 

<예제 코드_5>

fn do_twice<F>(mut func: F)
    where F: FnMut()
{
    func();
    func();
}

fn main() {
    let mut x: usize = 1;
    {
        let add_two_to_x = || x += 2;
        do_twice(add_two_to_x);
    }

    assert_eq!(x, 5);
}

 


 

<예제 코드_6>

fn consume_with_relish<F>(func: F)
    where F: FnOnce() -> String
{
    // 'func' consumes its captured varriables,
    // so it cannot be run more than once

    println!("Consumed: {}", func());

    println!("Delicious!");

    // Attempting to invoke `func()` again 
    // will throw a `use of moved value` error for `func`
}

fn main() {
    let x = String::from("x");
    let consume_and_return_x = move || x;
    consume_with_relish(consume_and_return_x);

    // `consume_and_return_x` can no longer be invoked at this point
}

 


 

<예제 코드_7>

trait Pilot {
    fn fly(&self);
}

trait Wizard {
    fn fly(&self);
}

struct Human;

impl Pilot for Human {
    fn fly(&self) {
        println!("This is your captain speaking.");
    }
}

impl Wizard for Human {
    fn fly(&self) {
        println!("Up");
    }
}

impl Human {
    fn fly(&self) {
        println!("&waving arms furiously*");
    }
}

fn main() {
    let person = Human;
    Pilot::fly(&person);
    Wizard::fly(&person);
    person.fly();
}

 


 

<예제 코드_8>

trait Animal {
    fn baby_name() -> String;
}

struct Dog;

impl Dog {
    fn baby_name() -> String {
        String::from("spot")
    }
}

impl Animal for Dog {
    fn baby_name() -> String {
        String::from("puppy")
    }
}

fn main() {
    println!("A baby dog is called a {}", <Dog as Animal>::baby_name());
}

 


 

<예제 코드_9>

use std::fmt;

struct Wrapper(Vec<String>);

impl fmt::Display for Wrapper {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "[{}]", self.0.join(", "))
    }
}

fn main() {
    let w = Wrapper(vec![String::from("hello"), String::from("world!")]);
    println!("w = {}", w);
}

 

 


 

<참조 1> https://rinthel.github.io/rust-lang-book-ko/ch19-03-advanced-traits.html

<참조 2> https://doc.rust-lang.org/std/ops/index.html

<참조 3>

 

 

'Rust' 카테고리의 다른 글

[Rust] Web-Server 제작 (48일차)  (0) 2023.01.30
[Rust] Thunk 예제 (47일차)  (0) 2023.01.29
[Rust] Pattern : 여러 예제 (45일차)  (0) 2023.01.28
[Rust] Trait 예제 (44일차)  (0) 2023.01.27

댓글