如何从结构中获取 fmt::Display 以将其显示在另一个结构的 fmt::Display 中?
How to get fmt::Display from a struct to display it in the fmt::Display of another struct?
我不确定如何命名这个问题,因为我是 Rust 的新手,所以请随时提出修改建议。
我有两个结构。一个是 Job
结构,其中包含一些数字,例如工作需要多长时间等。
另一个是 JobSequence
,其中包含 Vec()
个 Job
。
我为 Job
实现了 fmt::Display
特性,因此它以这种方式打印出它的三个数字:
(10, 12, 43)
现在,我想为 JobSequence
结构实现 fmt::Display
特性,以便它遍历向量中的每个 Job
并以这种方式显示它们:
(0, 10, 5)
(30, 10, 5)
(0, 10, 5)
(0, 10, 5)
(0, 10, 5)
我认为(?)我应该重用 Job
结构的已实现特征并使用它,以便它在某种程度上简单地将它们打印为半列表。这是我目前的实现,但我有一种草率的感觉,还有更好的方法:
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)
}
}
您可以 re-use Display
impl,方法是使用 {}
格式字符串将其直接传递给 write!
:
impl fmt::Display for JobSequence {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
for i in &self.job_sequence {
writeln!(f, "{}", i)?;
}
Ok(())
}
}
您可以在 the docs 中阅读有关格式化宏使用的不同特征的更多信息。 (普通的 {}
使用 std::fmt::Display
。)
我不确定如何命名这个问题,因为我是 Rust 的新手,所以请随时提出修改建议。
我有两个结构。一个是 Job
结构,其中包含一些数字,例如工作需要多长时间等。
另一个是 JobSequence
,其中包含 Vec()
个 Job
。
我为 Job
实现了 fmt::Display
特性,因此它以这种方式打印出它的三个数字:
(10, 12, 43)
现在,我想为 JobSequence
结构实现 fmt::Display
特性,以便它遍历向量中的每个 Job
并以这种方式显示它们:
(0, 10, 5)
(30, 10, 5)
(0, 10, 5)
(0, 10, 5)
(0, 10, 5)
我认为(?)我应该重用 Job
结构的已实现特征并使用它,以便它在某种程度上简单地将它们打印为半列表。这是我目前的实现,但我有一种草率的感觉,还有更好的方法:
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)
}
}
您可以 re-use Display
impl,方法是使用 {}
格式字符串将其直接传递给 write!
:
impl fmt::Display for JobSequence {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
for i in &self.job_sequence {
writeln!(f, "{}", i)?;
}
Ok(())
}
}
您可以在 the docs 中阅读有关格式化宏使用的不同特征的更多信息。 (普通的 {}
使用 std::fmt::Display
。)