当我有一个Display实现的枚举并且尝试将其打印为格式化格式时,我给它的宽度将被忽略。
use std::fmt;
enum TestEnum {
A,
B,
}
impl fmt::Display for TestEnum {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
TestEnum::A => write!(f, "A"),
TestEnum::B => write!(f, "B"),
}
}
}
fn main() {
println!("-{value:>width$}-", value = TestEnum::A, width = 3);
}
Run Code Online (Sandbox Code Playgroud)
我希望它能输出- A-,但它能输出-A-。
如果我将值替换为实际的字符串而不是枚举,那么它做对了,
println!("-{value:>width$}-", value = "A", width = 3);
Run Code Online (Sandbox Code Playgroud)
输出
- A-
Run Code Online (Sandbox Code Playgroud)
为什么忽略宽度?我需要做些什么?
通过write!在fmt实现中使用,您将覆盖其调用者提供的格式。
相反,您应该fmt自己调用字符串:
impl fmt::Display for TestEnum {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
TestEnum::A => "A".fmt(f),
TestEnum::B => "B".fmt(f),
}
}
}
Run Code Online (Sandbox Code Playgroud)
(永久链接到操场)
这将正确打印- A-。
| 归档时间: |
|
| 查看次数: |
75 次 |
| 最近记录: |