동등성 트레이트
Coddy Rust 여정의 객체 지향 프로그래밍 섹션에 포함된 레슨. 61개 중 38번째.
Rust에서 사용자 지정 struct의 two instances를 ==로 비교하는 것은 기본적으로 작동하지 않습니다. 컴파일러는 두 struct가 같은지 판단하는 방법을 알지 못합니다. PartialEq trait를 구현하여 이를 컴파일러에 알려줘야 합니다.
Debug 및 Copy와 마찬가지로 PartialEq도 자동으로 derive할 수 있습니다:
#[derive(PartialEq)]
struct Coordinate {
x: i32,
y: i32,
}
let a = Coordinate { x: 5, y: 10 };
let b = Coordinate { x: 5, y: 10 };
let c = Coordinate { x: 3, y: 7 };
println!("{}", a == b); // true
println!("{}", a == c); // false
derived되면 PartialEq는 struct의 각 fields를 비교합니다. 두 instances는 해당하는 모든 fields가 match할 때만 동일합니다.
Eq도 만나게 될 텐데, 이는 total equality를 나타내는 marker trait으로, 모든 값이 자기 자신과 같다는 의미입니다. 대부분의 타입이 이를 만족하지만, 부동 소수점 수는 그렇지 않습니다(NaN != NaN이기 때문입니다). 정수 필드가 있는 struct의 경우 다음 두 trait을 안전하게 derive할 수 있습니다.
#[derive(PartialEq, Eq)]
struct Coordinate {
x: i32,
y: i32,
}
Eq에는 고유한 메서드가 없습니다. 이는 해당 타입이 반사적 동치성을 가진다는 것을 나타낼 뿐입니다. 일부 표준 라이브러리 기능은 PartialEq에 더해 Eq를 요구하므로, 조건을 충족하는 타입에 대해 두 특성을 함께 derive하는 것이 일반적입니다.
챌린지
쉬움PartialEq 및 Eq traits를 통해 struct instances 간 비교가 가능함을 보여 주는 color matching system을 만들어 봅시다!
color comparison logic을 구성하기 위해 두 개의 파일을 만듭니다:
color.rs: 세 개의 public fields인red,green,blue(모두u8)를 가진 publicColorstruct를 Define합니다. 두 color를==를 사용해 비교할 수 있도록PartialEq와Eq를 모두 Derive합니다. Derive되면 Rust는 세 RGB components가 모두 정확히 일치하는 경우에만 두 color를 동일하다고 간주합니다.main.rs: color module을 가져오고 제공된 inputs를 사용해 두 개의Colorinstances를 만듭니다.==를 사용해 두 instances를 비교하고 일치하는지 여부를 Print합니다.
출력에는 두 color가 동일한지 여부가 표시되어야 합니다:
Color 1: rgb({r1}, {g1}, {b1})
Color 2: rgb({r2}, {g2}, {b2})
Colors match: {true/false}예를 들어 inputs가 255, 128, 0, 255, 128, 0인 경우:
Color 1: rgb(255, 128, 0)
Color 2: rgb(255, 128, 0)
Colors match: true그리고 inputs가 100, 100, 100, 200, 200, 200인 경우:
Color 1: rgb(100, 100, 100)
Color 2: rgb(200, 200, 200)
Colors match: false여섯 개의 inputs를 받습니다. 첫 번째 color의 RGB values(세 개의 values)가 먼저 오고, 그다음 두 번째 color의 RGB values(세 개의 values)가 옵니다. 각각을 u8로 parse합니다.
직접 해보기
mod color;
use color::Color;
fn main() {
// 여섯 개의 RGB 값을 읽습니다
let mut input = String::new();
std::io::stdin().read_line(&mut input).expect("Failed to read line");
let r1: u8 = input.trim().parse().expect("Invalid input");
input.clear();
std::io::stdin().read_line(&mut input).expect("Failed to read line");
let g1: u8 = input.trim().parse().expect("Invalid input");
input.clear();
std::io::stdin().read_line(&mut input).expect("Failed to read line");
let b1: u8 = input.trim().parse().expect("Invalid input");
input.clear();
std::io::stdin().read_line(&mut input).expect("Failed to read line");
let r2: u8 = input.trim().parse().expect("Invalid input");
input.clear();
std::io::stdin().read_line(&mut input).expect("Failed to read line");
let g2: u8 = input.trim().parse().expect("Invalid input");
input.clear();
std::io::stdin().read_line(&mut input).expect("Failed to read line");
let b2: u8 = input.trim().parse().expect("Invalid input");
// TODO: 파싱된 값을 사용하여 두 개의 Color 인스턴스를 생성합니다
// TODO: Color 1을 다음 형식으로 출력합니다: Color 1: rgb(r, g, b)
// TODO: Color 2를 다음 형식으로 출력합니다: Color 2: rgb(r, g, b)
// TODO: Compare the two colors using == and print: Colors match: {true/false}
}
이 레슨에는 짧은 퀴즈가 포함되어 있습니다. 레슨을 시작해 문제를 풀고 진행 상황을 기록하세요.
객체 지향 프로그래밍의 모든 레슨
직접 연습해 보세요: 온라인 Rust 컴파일러