Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

속성

속성(attribute)은 모듈, 크레이트 또는 아이템에 적용되는 메타데이터입니다. 이 메타데이터는 다음과 같은 용도로 사용될 수 있습니다:

속성은 #[outer_attribute] 또는 #![inner_attribute]와 같은 형태를 띠며, 이 둘의 차이점은 적용되는 위치에 있습니다.

  • #[outer_attribute]는 바로 뒤에 오는 아이템에 적용됩니다. 아이템의 예로는 함수, 모듈 선언, 상수, 구조체, 열거형 등이 있습니다. 다음은 #[derive(Debug)] 속성이 Rectangle 구조체에 적용된 예시입니다:

    #![allow(unused)]
    fn main() {
    #[derive(Debug)]
    struct Rectangle {
        width: u32,
        height: u32,
    }
    }
  • #![inner_attribute]는 자신을 감싸고 있는 아이템 (주로 모듈이나 크레이트)에 적용됩니다. 다시 말해, 이 속성은 자신이 위치한 전체 스코프에 적용되는 것으로 해석됩니다. 다음은 #![allow(unused_variables)]가 (main.rs에 위치할 경우) 전체 크레이트에 적용되는 예시입니다:

    #![allow(unused_variables)]
    
    fn main() {
        let x = 3; // 이것은 보통 사용되지 않는 변수에 대해 경고합니다.
    }

속성은 다양한 문법으로 인자를 받을 수 있습니다:

  • #[attribute = "value"]
  • #[attribute(key = "value")]
  • #[attribute(value)]

속성은 여러 값을 가질 수 있으며 여러 줄에 걸쳐 분리될 수도 있습니다:

#[attribute(value, value2)]


#[attribute(value, value2, value3,
            value4, value5)]