2025년 4월 26일 토요일

6-1강: 러스트 라이브러리(Copy, Clone, Drop)

1. Copy 예제

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

fn add_points(p1: Point, p2: Point) -> Point {
    Point {
        x: p1.x + p2.x,
        y: p1.y + p2.y,
    }
}

fn main() {
    let a = Point { x: 1, y: 2 };
    let b = Point { x: 3, y: 4 };

    // add_point의 인자로 들어가는 a, b는 copy트레잇에 의해 복제됩니다.
    let result = add_points(a, b);

    println!("{:?}", a); // a에 접근 가능
    println!("{:?}", b); // b에 접근 가능
    println!("{:?}", result);
}
/*실행결과
Point { x: 1, y: 2 }
Point { x: 3, y: 4 }
Point { x: 4, y: 6 }
*/

2. Clone 예제
// Clone trait을 구현하지 않은 타입은 clone() 메서드를 사용할 수 없다.
#[derive(Debug)]
struct Person {
    name: String,
    age: u32,
    cloned: bool,
}

impl Clone for Person {
    fn clone(&self) -> Self {
        Person {
            name: self.name.clone(),
            age: self.age,
            cloned: true
        }
    }
}

fn main() {
    let person1 = Person {
        name: String::from("루나"),
        age: 10,
        cloned: false
    };

    // person1을 복제합니다. 소유권을 잃지 않습니다.
    let person2 = person1.clone();

    println!("{:?}", person1);
    println!("{:?}", person2);
}

/*실행결과
Person { name: "루나", age: 10, cloned: false }
Person { name: "루나", age: 10, cloned: true }
*/

3. Drop 예제
// 객체가 메모리에서 벗어날 때 수행해야 할 작업 지정
struct Book {
    title: String,
}

impl Drop for Book {
    // Drop트레잇을 구현합니다.
    fn drop(&mut self) {
        println!("Book객체 해제: {}", self.title);
    }
}

fn main() {
    {
        let book = Book { title: String::from("러스트") };
    } // book의 Drop트레잇이 자동으로 호출됩니다.
}

/*실행결과
Book객체 해제: 러스트
*/

댓글 없음:

댓글 쓰기