Write a struct with an enum field, a method and a trait implementation
Model a to-do item: an enum Priority with the variants Low and High, a struct Task with a title and a priority, an impl Task block with a constructor and a method, and the trait std::fmt::Display implemented for Task.
Constraints:
Task::new(title: &str, priority: Priority)returns aTaskthat owns its title.is_urgent(&self) -> boolistrueonly forPriority::Highand does not consume the task.{}prints[high] Write reportor[low] Water plants; the build has no warnings.
use std::fmt;
enum Priority {
Low,
High,
}
struct Task {
// your code here
}
// your code here: impl Task, impl fmt::Display for Task
fn main() {
let a = Task::new("Write report", Priority::High);
let b = Task::new("Water plants", Priority::Low);
println!("{a} {}", a.is_urgent()); // [high] Write report true
println!("{b} {}", b.is_urgent()); // [low] Water plants false
}Write the implementation.
Declare enum Priority { Low, High } and struct Task { title: String, priority: Priority }; impl Task adds new returning Self and is_urgent(&self), a match on self.priority; and impl fmt::Display for Task prints [high] title.
- Expecting
#[derive(Display)]to exist instead of writingimpl fmt::Display - Writing methods inside the
structbody, as in a class, instead of in animplblock - Storing
&strin the field without a lifetime instead of an ownedString
- How would you let
Taskprint with{:?}as well as with{}? - Why does
is_urgenttake&selfrather thanself?
The enum Priority describes two levels of urgency, and the struct Task keeps its title as an owned String, so a task does not depend on the string it was built from and the field needs no lifetime. Behaviour lives apart from the data, in an impl block: the associated function new builds the literal through Self, and the method is_urgent takes &self because reading a field is all it needs.
use std::fmt;
enum Priority {
Low,
High,
}
struct Task {
title: String,
priority: Priority,
}
impl Task {
fn new(title: &str, priority: Priority) -> Self {
Self {
title: String::from(title),
priority,
}
}
fn is_urgent(&self) -> bool {
match self.priority {
Priority::High => true,
Priority::Low => false,
}
}
}
impl fmt::Display for Task {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let label = match self.priority {
Priority::Low => "low",
Priority::High => "high",
};
write!(f, "[{label}] {}", self.title)
}
}
fn main() {
let a = Task::new("Write report", Priority::High);
let b = Task::new("Water plants", Priority::Low);
println!("{a} {}", a.is_urgent()); // [high] Write report true
println!("{b} {}", b.is_urgent()); // [low] Water plants false
}Display cannot be derived (#[derive(Display)] does not compile), so it is implemented in its own impl fmt::Display for Task block, where write! builds the text for {}. Both match expressions are exhaustive: add a third variant to Priority and the compiler points at every place that must handle it. The build is warning-free: main constructs both variants and both fields are read.