Summary - Enums
- Rust course
- Beginner
- Lesson 82/115
- 5 min
Combine data-carrying enums and Option to model an IP address type.
Enums summary
An enum states that a value is one of a fixed set of options. Variants may carry no data, or carry data in tuple or struct form. match forces every variant to be handled. Option<T> (Some/None) replaces null and is used with helpers like unwrap_or, map and is_some. Methods can be added to enums with impl.
Methods on an enum
In enums carrying data, a method does a separate calculation for each variant with match self:
enum Sekil {
Daire(f64),
Kare(f64),
}
impl Sekil {
fn alan(&self) -> f64 {
match self {
Sekil::Daire(r) => std::f64::consts::PI * r * r,
Sekil::Kare(a) => a * a,
}
}
}When a new shape is added, the compiler tells you to update the alan method.
Practice Shape areas
Write the Sekil enum above and the alan method. Print the areas of Sekil::Daire(1.0) and Sekil::Kare(2.0) with the {:.2} format, separated by a space.
Starter code
fn main() {
// buraya yaz
}Sample solution
enum Sekil {
Daire(f64),
Kare(f64),
}
impl Sekil {
fn alan(&self) -> f64 {
match self {
Sekil::Daire(r) => std::f64::consts::PI * r * r,
Sekil::Kare(a) => a * a,
}
}
}
fn main() {
println!("{:.2} {:.2}", Sekil::Daire(1.0).alan(), Sekil::Kare(2.0).alan());
}Expected output
3.14 4.00
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What determines the memory size of an <code>enum Sekil { Daire(f64), Kare(f64) }</code> value?
- The largest variant + a discriminant tag Correct answer
- The sum of all variants
- Always 1 byte
- It changes at runtime
Explanation: Since an enum value is one variant at a time, room is made for the largest one, plus a tag saying which variant it is.
2 Option variant
let x: Option<i32> = ____(4);
let x: Option<i32> = Some(4);
Explanation: If there is a value, it is wrapped in Some.
3 Group summary
| Term | Meaning |
|---|---|
enum A { X, Y } |
Set of options |
B::X(5) |
Variant with data |
Option<T> |
Instead of null |
match self |
Method by variant |