14.1 Derive
컴파일러는 #[derive] 속성(attribute)를 통해 몇 trait를 위한 기본적인 구현을 제공할 수 있다. 이들 trait들은 더 복잡한 동작이 요구될 때 수동으로 구현될 수 있다.
다음 목록들은 derive 가능한 traits이다:
- trait 비교자:
Eq,PartialEq,Ord,PartialOrd Clone,&T를 복사하여T생성하려면.- [
Copy][copy], 'move 의미문' 대신 'copy 의미문' 타입으로 주려면. Hash,&T에서 해시를 계산하려면.Default, 데이터 타입의 빈 인스턴스를 만드려면.Zero, 숫자 데이터 타입의 빈 인스턴스를 만드려면.Debug,{:?}형식자를 사용해 값을 형식화하려면.
// 비교할 수 있는 튜플 구조체 `Centimeters`
#[derive(PartialEq, PartialOrd)]
struct Centimeters(f64);
// 출력할 수 있는 튜플 구조체 `Inches`
#[derive(Debug)]
struct Inches(i32);
impl Inches {
fn to_centimeters(&self) -> Centimeters {
let &Inches(inches) = self;
Centimeters(inches as f64 * 2.54)
}
}
// 추가 속성이 없는 튜플 구조체 `Seconds`
struct Seconds(i32);
fn main() {
let _one_second = Seconds(1);
// 에러: `Seconds`는 출력될 수 없다. `Debug` trait이 구현되지 않았다.
//println!("One second looks like: {:?}", _one_second);
// TODO ^ 해당 라인의 주석을 제거해보세요.
// 에러: `Seconds`는 비교될 수 없다. `PartialEq` trait이 구현되지 않았다.
//let _this_is_true = (_one_second == _one_second);
// TODO ^ 해당 라인의 주석을 제거해보세요.
let foot = Inches(12);
println!("One foot equals {:?}", foot);
let meter = Centimeters(100.0);
let cmp =
if foot.to_centimeters() < meter {
"smaller"
} else {
"bigger"
};
println!("One foot is {} than one meter.", cmp);
}See also:
[copy]: