Struct, Enum และ Trait
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
โจทย์ทั้งหมด