【发布时间】:2019-05-06 19:51:27
【问题描述】:
我有一个类型Clock:
#[derive(Debug, PartialEq)]
pub struct Clock {
hours: i32,
minutes: i32,
}
为此实现了一些特征。例如:
#[allow(clippy::match_bool)]
impl fmt::Display for Clock {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
let tmp = match (self.hours < 10, self.minutes < 10) {
(false, false) => ("", self.hours, "", self.minutes),
(false, true) => ("", self.hours, "0", self.minutes),
(true, false) => ("0", self.hours, "", self.minutes),
(true, true) => ("0", self.hours, "0", self.minutes),
};
write!(
formatter,
"{}",
format!("{}{}:{}{}", tmp.0, tmp.1, tmp.2, tmp.3)
)
}
}
我想实现String::from(Clock::new(...))。我该怎么做?
我尝试过:
impl convert::From<Clock> for String {
fn from(clock: Clock) -> String {
clock.to_string()
}
}
【问题讨论】:
-
还有:What is the easiest way to pad a string with 0 to the left? —
write!(formatter, "{:02}:{:02}", self.hours, self.minutes) -
@Shepmaster,谢谢。在提出问题后,我自己决定了工作解决方案。
标签: rust