【问题标题】:How do I implement String::from for my type?如何为我的类型实现 String::from?
【发布时间】: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()
    }
}

【问题讨论】:

标签: rust


【解决方案1】:

可行的解决方案:

impl From<Clock> for String {
    fn from(clock: Clock) -> String {
        clock.to_string()
    }
}

impl fmt::Display for Clock {
    fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
        write!(
            formatter,
            "{}",
            format!("{:02}:{:02}", self.hours, self.minutes)
        )
    }
}

【讨论】:

  • 为什么不write!(formatter, "{:2}:{:2}", self.hours, self.minutes)
  • 具体来说,使用format! 会导致不需要的内存分配。另外,您不想要零填充数字吗?
猜你喜欢
  • 2015-10-08
  • 2021-05-19
  • 1970-01-01
  • 2023-02-08
  • 2016-11-08
  • 1970-01-01
  • 1970-01-01
  • 2016-09-17
相关资源
最近更新 更多