100 Exercises To Learn Rust - 3.5 encapsulation 풀기

impl Ticket {
        pub fn new(title: String, description: String, status: String) -> Ticket {
            if title.is_empty() {
                panic!("Title cannot be empty");
            }
            if title.len() > 50 {
                panic!("Title cannot be longer than 50 bytes");
            }
            if description.is_empty() {
                panic!("Description cannot be empty");
            }
            if description.len() > 500 {
                panic!("Description cannot be longer than 500 bytes");
            }
            if status != "To-Do" && status != "In Progress" && status != "Done" {
                panic!("Only `To-Do`, `In Progress`, and `Done` statuses are allowed");
            }

            Ticket {
                title,
                description,
                status,
            }
        }

        // TODO: Ticket 구조체에 3개의 공개 메서드를 추가하세요.
        // - `title`은 `title` 필드를 반환합니다.
        // - `description`은 `description` 필드를 반환합니다.
        // - `status`는 `status` 필드를 반환합니다.
    }

풀이:

impl Ticket {
        pub fn new(title: String, description: String, status: String) -> Ticket {
            if title.is_empty() {
                panic!("Title cannot be empty");
            }
            if title.len() > 50 {
                panic!("Title cannot be longer than 50 bytes");
            }
            if description.is_empty() {
                panic!("Description cannot be empty");
            }
            if description.len() > 500 {
                panic!("Description cannot be longer than 500 bytes");
            }
            if status != "To-Do" && status != "In Progress" && status != "Done" {
                panic!("Only `To-Do`, `In Progress`, and `Done` statuses are allowed");
            }

            Ticket {
                title,
                description,
                status,
            }
        }

        pub fn title(&self) -> &str {
            &self.title
        }
        pub fn description(self) -> String {
            self.description
        }
        pub fn status(&self) -> String {
            self.status.clone()
        }
    }

 

접근자를 생성할 때 소유권 개념을 이용해 다양하게 생성해볼 수 있다.

 

title()&self로 대여해 문자열 슬라이스(&str)를 반환하는 방식으로,

 

description()self의 소유권을 아예 받아와서 반환하는 방식으로,

 

status()&self로 대여한 후, 그냥 status를 반환하게 되면 &self로 접근하는 status는 참조일 뿐이므로 소유권을 이전할 수 없게 된다. 따라서 clone()으로 복사본을 만들어 반환시킨다.