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 रिव्यू के साथ।
सभी चैलेंज