作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我想让用户决定我的结构的格式,并将其传递给它下面的结构。
例如:
struct Coordinates {
x: i64,
y: i64,
}
impl fmt::Display for Coordinates {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "Coordinates(x: {}, y: {})", self.x, self.y)
}
}
impl fmt::LowerHex for Coordinates {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "Coordinates(x: {:x}, y: {:x})", self.x, self.y)
}
}
我希望它像这样工作
let c = Coordinates { x: 10, y: 20 };
println!("{}", c);
// => Coordinates(x: 10, y: 20)
println!("{:010x}, c");
// => Coordinates(x: 000000000a, y: 0000000014)
我想将 "{:010x}"
直接传递给 "Coordinates(x: {here}, y: {and here})"
。我怎样才能做到这一点?
最佳答案
您可以编写 self.x.fmt(f)
以使用相同的格式化程序将调用转发给其内部成员。
use std::fmt;
struct Coordinates {
x: i64,
y: i64,
}
impl fmt::Display for Coordinates {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "Coordinates(x: ")?;
self.x.fmt(f)?;
write!(f, ", y: ")?;
self.y.fmt(f)?;
write!(f, ")")?;
Ok(())
}
}
impl fmt::LowerHex for Coordinates {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "Coordinates(x: ")?;
self.x.fmt(f)?;
write!(f, ", y: ")?;
self.y.fmt(f)?;
write!(f, ")")?;
Ok(())
}
}
fn main() {
let c = Coordinates { x: 10, y: 20 };
assert_eq!(format!("{}", c), "Coordinates(x: 10, y: 20)");
assert_eq!(
format!("{:010x}", c),
"Coordinates(x: 000000000a, y: 0000000014)"
);
}
关于rust - 如何将格式字符串选项从用户传递到我的组件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49197217/
我是一名优秀的程序员,十分优秀!