구조체, 열거형, 트레이트
Rust Enums
A type that is exactly one of several variants, where each variant can carry its own data.
배울 내용
- Variants with data
- match on an enum
- Methods on enums
enum Shape
ShapeCircle(f64)Rectangle { width, height }Point
One of several shapes
An enum is a type whose value is exactly one of a fixed list of variants. In Rust each variant can carry its own data, so one enum can describe several different shapes of information.
Circle carries one number, Rectangle carries two named fields and Point carries nothing. match must handle every variant, so the compiler reports an error if you add a variant and forget a case. {:.2} prints two digits after the decimal point.
핵심 포인트
- Each variant can hold different data.
- match must cover every variant.
- Forgetting one is a compile error.
실행 가능한 Rust 예제
Rust
main.rs
enum Shape {
Circle(f64),
Rectangle { width: f64, height: f64 },
Point,
}
impl Shape {
fn area(&self) -> f64 {
match self {
Shape::Circle(radius) => 3.14159 * radius * radius,
Shape::Rectangle { width, height } => width * height,
Shape::Point => 0.0,
}
}
}
fn main() {
let shapes = [
Shape::Circle(1.0),
Shape::Rectangle { width: 2.0, height: 3.5 },
Shape::Point,
];
for shape in &shapes {
println!("{:.2}", shape.area());
}
}
3.14
7.00
0.00연습
예제를 온라인 컴파일러에서 열고 값을 바꾸거나 한 줄을 추가한 다음, 실행하기 전에 출력을 예상해 보세요. 그런 다음 일부러 코드를 망가뜨리고 컴파일러 메시지를 읽어 보세요.
이 레슨을 마쳤나요?
학습 완료로 표시하면 진행 상황을 기록할 수 있습니다.
진행 상황이 이 브라우저에 저장되어 있습니다 로그인하면 모든 기기에서 이어갈 수 있습니다.
챌린지로 연습하기
이 레슨에서 배운 내용으로 실제 문제를 풀어 보세요. 모든 챌린지는 브라우저에서 실행되며 즉시 테스트와 AI 리뷰를 받을 수 있습니다.
모든 챌린지