'How to get fmt::Display from a struct to display it in the fmt::Display of another struct?
Im not sure how to name this question as I am new to Rust so feel free to suggest edits.
I have two structs. One is a Job struct, which contains a few numbers like how long a job takes, etc.
The other is a JobSequence, which contains a Vec() of Jobs.
I implemented the fmt::Display trait for the Job so that it prints out its three number in this way:
(10, 12, 43)
Now, I would like to implement the fmt::Display trait for the JobSequence struct so that it iterates over each Job in the vector and displays them in this way:
(0, 10, 5)
(30, 10, 5)
(0, 10, 5)
(0, 10, 5)
(0, 10, 5)
I think(?) I should reuse the implemented trait of the Job struct and use it so that it simply, in a way, printouts them as a semi-list. This is my current implementation, but i have a feeling that is sloppy and there is a better way:
pub struct JobSequence {
pub job_sequence: Vec<Job>,
}
impl fmt::Display for JobSequence {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let mut final_output = String::new();
for i in &self.job_sequence {
final_output.push_str(i.to_string().as_str());
final_output.push_str("\n");
}
write!(f, "{}", final_output)
}
}
Solution 1:[1]
You can re-use the the Display impl by passing it directly to write! with the {} format string:
impl fmt::Display for JobSequence {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
for i in &self.job_sequence {
writeln!(f, "{}", i)?;
}
Ok(())
}
}
You can read more about the different traits used by the formatting macros in the docs. (A plain {} uses std::fmt::Display.)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Dogbert |
