100 Exercises To Learn Rust - 4.13 Drop 풀기

목차

풀이

// TODO: Drob bomb를 구현하세요.
// 불필요한 drop이 발생하면 패닉을 일으킵니다.
// 요구하는 API는 테스트에서 확인할 수 있습니다.

struct DropBomb {
    defused: bool,
}

impl Drop for DropBomb {
    fn drop(&mut self) {
        if !self.defused {
            panic!();
        }
    }
}
impl DropBomb {
    pub fn new() -> Self{
        DropBomb {
            defused: false,
        }
    }

    pub fn defuse(&mut self) {
        self.defused = true;
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    #[should_panic]
    fn test_drop_bomb() {
        let bomb = DropBomb::new();
        // The bomb should panic when dropped
    }

    #[test]
    fn test_defused_drop_bomb() {
        let mut bomb = DropBomb::new();
        bomb.defuse();
        // The bomb should not panic when dropped
        // since it has been defused
    }
}

 

단순히 drop이 동작한다면 패닉이 발생하고, defuse()를 호출하면 패닉이 발생하지 않도록 해야 한다.

 

이를 위해 defuse 상태를 관리할 수 있도록 구조체에 불리언 타입 defused 필드를 둔다.

 

new()로 생성할 시 defused는 거짓이고, defuse() 메서드를 호출하면 참이 된다.

 

defused 필드가 거짓인 경우에는 패닉을 발생시키도록 drop 트레이트를 구현한다.