我有这个示例代码。
use std::fmt;
struct MyStruct {
mystring: String
}
impl fmt::Display for MyStruct {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "^.^ My String is *{}*. ^.^", self.mystring)
}
}
fn main() {
let mystruct = MyStruct { mystring: "GOAT".to_string() };
println!("|{:^80}|", mystruct);
println!("|{:^80}|", "^.^ My String is *GOAT*. ^.^")
}
(游乐场(
我希望无论MyStruct::fmt()
实现的输出是什么,由于{:^80}
说明符,它都将被写入一个80个字符宽的字段,并与中心对齐。事实并非如此。输出不尊重说明符,这与我简单地编写{}
是一样的。
这是我的例子的输出:
|^.^ My String is *GOAT*. ^.^|
| ^.^ My String is *GOAT*. ^.^ |
我希望这两行看起来一模一样。
如何实现格式化程序,使其尊重格式化时使用的格式说明符?
pad()
函数尊重格式化标志,但它需要&str
,因此需要调用format!()
:
impl fmt::Display for MyStruct {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.pad(&format!("^.^ My String is *{}*. ^.^", self.mystring))
}
}
游乐场。