gpt4 book ai didi

rust - 如何将格式字符串选项从用户传递到我的组件?

转载 作者:行者123 更新时间:2023-11-29 07:48:06 25 4
gpt4 key购买 nike

我想让用户决定我的结构的格式,并将其传递给它下面的结构。

例如:

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com