destructors에 대해 배울 때, drop function에 대해 얘기했었다.
- 해당 type이 차지하던 memory(std::mem::size_of bytes)를 회수한다.
- 해당 값이 관리하는 어떤 additional resource들(String의 heap buffer같은) 또한 clean up한다.
Drop trait은 어디서 올까?
pub trait Drop {
fn drop(&mut self);
}
Drop trait은 compiler가 당신에게 자동으로 제공하는 것을 넘어,
당신의 types에 대한 additional cleanup logic을 정의하는 mechanism이다.
drop method에 넣은 것이 무엇이든, value가 scope를 벗어나면 실행될 것이다.
Copy trait에 대해 얘기할 때, type이 additional resources를 관리하면
Copy를 구현할 수 없다고 했다.
근데 여기서 이상한게 있다.
compiler는 어떻게 type이 additional resources를 관리하는 것을 알까?
Drop trait 구현이다!
만약 당신의 type이 explicit drop implementatioin을 갖고 있다면,
compiler는 당신의 type이 additional resources를 갖고 있다고 추측할 것이고,
Copy를 구현하지 못하게 할 것이다.
// This is a unit struct, i.e. a struct with no fields.
#[derive(Clone, Copy)]
struct MyType;
impl Drop for MyType {
fn drop(&mut self) {
// We don't need to do anything here,
// it's enough to have an "empty" Drop implementation
}
}
위 코드처럼 구현하면
error[E0184]: the trait `Copy` cannot be implemented for this type; the type has a destructor
--> src/lib.rs:2:17
|
2 | #[derive(Clone, Copy)]
| ^^^^ `Copy` not allowed on types with destructors
이렇게 compile error가 뜬다.
13_drop exercise는 new를 인자 없이 default로 만드는 법을 몰라서 해맸다.
아이디어 자체는 맞았고 solution을 참고해서 했다.

이번 chapter에서는 서로 다른 traits를 다뤘다.
하지만 이것은 빙산의 일각이다.
기억할게 많은 것처럼 보이지만 걱정하지 말란다.
traits를 자주자주 쓰다보면 익숙해지고 자연스러워질 것이라고 한다.
Traits은 강력하지만, 남용해서는 안된다.
아래 guidelines를 기억해라.
- 하나의 type에 대해서만 불려지는 function을 generic으로 만들지마라.
- 하나의 implementation을 갖는 trait은 만들지마라.
- 당신의 types에 대한 standard traits(Debug, PartialEq 등등)를 implement해라.
- 다른 곳에서 제공하는 traits를 적극적으로 활용해라.
- 테스트할 때, 주로 generic을 사용하는데 이는 복잡성을 증가시킬 수 있으니 다른 대안도 생각해라.
14_outro exercise는 지금까지 배운 것을 활용했다.
연산자 overloading, traits 사용자 정의, add 연산에 대한 정의 등등
이것 역시 접근은 잘 했으나, 중간에 조합을 잘못해서 늪에 빠졌다.
더 연습해봐야겠다.

solution을 보니, 내가 구현한 것과 약간 차이가 있었다.
나는 직접 type명을 많이 사용했는데
solution은 self를 많이 사용했다.
이를 동일시여기고 생각하며 코딩해야겠다.
chapter4는 생각보다 어려웠다.
traits의 개념이 어려웠고, 할 수 있는 행동이 많다는 것을 알았다.
이제 문법적인 측면에서는 어느정도 익숙해졌다.
chapter5 이후의 과정도 파이팅이다.
'Rust Programming' 카테고리의 다른 글
| [Rust] 5. Ticket v2: Variants with data, Branching(if let and let/else), Nullability (0) | 2024.08.01 |
|---|---|
| [Rust] 5. Ticket v2: Enums, Branching(match) (0) | 2024.07.31 |
| [Rust] 4. Traits: Associated and generic types, Clone trait, Copy trait (0) | 2024.07.30 |
| [Rust] 4. Traits: Deref trait, Sized trait, From trait (0) | 2024.07.29 |
| [Rust] 4. Traits: Derive macros, Trait bounds, String slices (0) | 2024.07.26 |