pub struct Formatter<'a> { /* private fields */ }
Expand description
Implementations§
source§impl<'a> Formatter<'a>
impl<'a> Formatter<'a>
sourcepub fn pad_integral(
&mut self,
is_nonnegative: bool,
prefix: &str,
buf: &str
) -> Result<(), Error>
pub fn pad_integral( &mut self, is_nonnegative: bool, prefix: &str, buf: &str ) -> Result<(), Error>
对已经发出到 str 中的整数执行正确的填充。 str 不应 包含整数的符号,该符号将通过此方法添加。
Arguments
-
is_nonnegative - 原始整数是正数还是零。
-
prefix - 如果提供了 ‘#’ 字符 (Alternate),则这是放在数字前面的前缀。
-
buf - 数字已格式化为的字节数组
此函数将正确说明提供的标志以及最小宽度。 它不会考虑精度。
Examples
use std::fmt;
struct Foo { nb: i32 }
impl Foo {
fn new(nb: i32) -> Foo {
Foo {
nb,
}
}
}
impl fmt::Display for Foo {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
// 我们需要从数字输出中删除 "-"。
let tmp = self.nb.abs().to_string();
formatter.pad_integral(self.nb >= 0, "Foo ", &tmp)
}
}
assert_eq!(format!("{}", Foo::new(2)), "2");
assert_eq!(format!("{}", Foo::new(-1)), "-1");
assert_eq!(format!("{}", Foo::new(0)), "0");
assert_eq!(format!("{:#}", Foo::new(-1)), "-Foo 1");
assert_eq!(format!("{:0>#8}", Foo::new(-1)), "00-Foo 1");
Runsourcepub fn pad(&mut self, s: &str) -> Result<(), Error>
pub fn pad(&mut self, s: &str) -> Result<(), Error>
应用指定的相关格式设置标志后,此函数将获取一个字符串切片并将其发送到内部缓冲区。 泛型字符串可识别的标志为:
- width - 发射的最小宽度
- fill/align - 如果需要填充提供的字符串,要发出什么以及在哪里发出
- precision - 发出的最大长度,如果字符串长于该长度,则字符串将被截断
值得注意的是,此函数将忽略 flag
参数。
Examples
use std::fmt;
struct Foo;
impl fmt::Display for Foo {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter.pad("Foo")
}
}
assert_eq!(format!("{Foo:<4}"), "Foo ");
assert_eq!(format!("{Foo:0>4}"), "0Foo");
Runsourcepub fn write_str(&mut self, data: &str) -> Result<(), Error>
pub fn write_str(&mut self, data: &str) -> Result<(), Error>
将一些数据写入此格式化程序中包含的底层缓冲区。
Examples
use std::fmt;
struct Foo;
impl fmt::Display for Foo {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter.write_str("Foo")
// 这相当于:
// write!(formatter, "Foo")
}
}
assert_eq!(format!("{Foo}"), "Foo");
assert_eq!(format!("{Foo:0>8}"), "Foo");
Runsourcepub fn write_fmt(&mut self, fmt: Arguments<'_>) -> Result<(), Error>
pub fn write_fmt(&mut self, fmt: Arguments<'_>) -> Result<(), Error>
将一些格式化的信息写入此实例。
Examples
use std::fmt;
struct Foo(i32);
impl fmt::Display for Foo {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter.write_fmt(format_args!("Foo {}", self.0))
}
}
assert_eq!(format!("{}", Foo(-1)), "Foo -1");
assert_eq!(format!("{:0>8}", Foo(2)), "Foo 2");
Runsourcepub fn flags(&self) -> u32
👎Deprecated since 1.24.0: use the sign_plus
, sign_minus
, alternate
, or sign_aware_zero_pad
methods instead
pub fn flags(&self) -> u32
sign_plus
, sign_minus
, alternate
, or sign_aware_zero_pad
methods instead格式化标志
1.5.0 · sourcepub fn fill(&self) -> char
pub fn fill(&self) -> char
对齐时用作 ‘fill’ 的字符。
Examples
use std::fmt;
struct Foo;
impl fmt::Display for Foo {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
let c = formatter.fill();
if let Some(width) = formatter.width() {
for _ in 0..width {
write!(formatter, "{c}")?;
}
Ok(())
} else {
write!(formatter, "{c}")
}
}
}
// 我们使用 ">" 在右边设置对齐方式。
assert_eq!(format!("{Foo:G>3}"), "GGG");
assert_eq!(format!("{Foo:t>6}"), "tttttt");
Run1.28.0 · sourcepub fn align(&self) -> Option<Alignment>
pub fn align(&self) -> Option<Alignment>
指示请求对齐方式的标志。
Examples
use std::fmt::{self, Alignment};
struct Foo;
impl fmt::Display for Foo {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
let s = if let Some(s) = formatter.align() {
match s {
Alignment::Left => "left",
Alignment::Right => "right",
Alignment::Center => "center",
}
} else {
"into the void"
};
write!(formatter, "{s}")
}
}
assert_eq!(format!("{Foo:<}"), "left");
assert_eq!(format!("{Foo:>}"), "right");
assert_eq!(format!("{Foo:^}"), "center");
assert_eq!(format!("{Foo}"), "into the void");
Run1.5.0 · sourcepub fn width(&self) -> Option<usize>
pub fn width(&self) -> Option<usize>
(可选) 指定输出应为的整数宽度。
Examples
use std::fmt;
struct Foo(i32);
impl fmt::Display for Foo {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
if let Some(width) = formatter.width() {
// 如果我们收到一个宽度,我们就用它
write!(formatter, "{:width$}", format!("Foo({})", self.0), width = width)
} else {
// 否则我们没什么特别的
write!(formatter, "Foo({})", self.0)
}
}
}
assert_eq!(format!("{:10}", Foo(23)), "Foo(23) ");
assert_eq!(format!("{}", Foo(23)), "Foo(23)");
Run1.5.0 · sourcepub fn precision(&self) -> Option<usize>
pub fn precision(&self) -> Option<usize>
可选地为数字类型指定精度。 或者,为字符串类型的最大宽度。
Examples
use std::fmt;
struct Foo(f32);
impl fmt::Display for Foo {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
if let Some(precision) = formatter.precision() {
// 如果我们收到了精度,我们就会使用它。
write!(formatter, "Foo({1:.*})", precision, self.0)
} else {
// 否则我们默认为 2.
write!(formatter, "Foo({:.2})", self.0)
}
}
}
assert_eq!(format!("{:.4}", Foo(23.2)), "Foo(23.2000)");
assert_eq!(format!("{}", Foo(23.2)), "Foo(23.20)");
Run1.5.0 · sourcepub fn sign_plus(&self) -> bool
pub fn sign_plus(&self) -> bool
确定是否指定了 +
标志。
Examples
use std::fmt;
struct Foo(i32);
impl fmt::Display for Foo {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
if formatter.sign_plus() {
write!(formatter,
"Foo({}{})",
if self.0 < 0 { '-' } else { '+' },
self.0.abs())
} else {
write!(formatter, "Foo({})", self.0)
}
}
}
assert_eq!(format!("{:+}", Foo(23)), "Foo(+23)");
assert_eq!(format!("{:+}", Foo(-23)), "Foo(-23)");
assert_eq!(format!("{}", Foo(23)), "Foo(23)");
Run1.5.0 · sourcepub fn sign_minus(&self) -> bool
pub fn sign_minus(&self) -> bool
确定是否指定了 -
标志。
Examples
use std::fmt;
struct Foo(i32);
impl fmt::Display for Foo {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
if formatter.sign_minus() {
// 您想要一个减号? 有一个!
write!(formatter, "-Foo({})", self.0)
} else {
write!(formatter, "Foo({})", self.0)
}
}
}
assert_eq!(format!("{:-}", Foo(23)), "-Foo(23)");
assert_eq!(format!("{}", Foo(23)), "Foo(23)");
Run1.5.0 · sourcepub fn alternate(&self) -> bool
pub fn alternate(&self) -> bool
确定是否指定了 #
标志。
Examples
use std::fmt;
struct Foo(i32);
impl fmt::Display for Foo {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
if formatter.alternate() {
write!(formatter, "Foo({})", self.0)
} else {
write!(formatter, "{}", self.0)
}
}
}
assert_eq!(format!("{:#}", Foo(23)), "Foo(23)");
assert_eq!(format!("{}", Foo(23)), "23");
Run1.5.0 · sourcepub fn sign_aware_zero_pad(&self) -> bool
pub fn sign_aware_zero_pad(&self) -> bool
确定是否指定了 0
标志。
Examples
use std::fmt;
struct Foo(i32);
impl fmt::Display for Foo {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
assert!(formatter.sign_aware_zero_pad());
assert_eq!(formatter.width(), Some(4));
// 我们忽略格式化程序的选项。
write!(formatter, "{}", self.0)
}
}
assert_eq!(format!("{:04}", Foo(23)), "23");
Run1.2.0 · sourcepub fn debug_struct<'b>(&'b mut self, name: &str) -> DebugStruct<'b, 'a>
pub fn debug_struct<'b>(&'b mut self, name: &str) -> DebugStruct<'b, 'a>
创建一个 DebugStruct
构建器,该构建器旨在帮助创建结构体的 fmt::Debug
实现。
Examples
use std::fmt;
use std::net::Ipv4Addr;
struct Foo {
bar: i32,
baz: String,
addr: Ipv4Addr,
}
impl fmt::Debug for Foo {
fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt.debug_struct("Foo")
.field("bar", &self.bar)
.field("baz", &self.baz)
.field("addr", &format_args!("{}", self.addr))
.finish()
}
}
assert_eq!(
"Foo { bar: 10, baz: \"Hello World\", addr: 127.0.0.1 }",
format!("{:?}", Foo {
bar: 10,
baz: "Hello World".to_string(),
addr: Ipv4Addr::new(127, 0, 0, 1),
})
);
Run1.2.0 · sourcepub fn debug_tuple<'b>(&'b mut self, name: &str) -> DebugTuple<'b, 'a>
pub fn debug_tuple<'b>(&'b mut self, name: &str) -> DebugTuple<'b, 'a>
创建一个 DebugTuple
构建器,该构建器旨在协助创建元组结构体的 fmt::Debug
实现。
Examples
use std::fmt;
use std::marker::PhantomData;
struct Foo<T>(i32, String, PhantomData<T>);
impl<T> fmt::Debug for Foo<T> {
fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt.debug_tuple("Foo")
.field(&self.0)
.field(&self.1)
.field(&format_args!("_"))
.finish()
}
}
assert_eq!(
"Foo(10, \"Hello\", _)",
format!("{:?}", Foo(10, "Hello".to_string(), PhantomData::<u8>))
);
Run1.2.0 · sourcepub fn debug_list<'b>(&'b mut self) -> DebugList<'b, 'a>
pub fn debug_list<'b>(&'b mut self) -> DebugList<'b, 'a>
创建一个 DebugList
构建器,该构建器旨在帮助为类似列表的结构创建 fmt::Debug
实现。
Examples
use std::fmt;
struct Foo(Vec<i32>);
impl fmt::Debug for Foo {
fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt.debug_list().entries(self.0.iter()).finish()
}
}
assert_eq!(format!("{:?}", Foo(vec![10, 11])), "[10, 11]");
Run1.2.0 · sourcepub fn debug_set<'b>(&'b mut self) -> DebugSet<'b, 'a>
pub fn debug_set<'b>(&'b mut self) -> DebugSet<'b, 'a>
创建一个 DebugSet
构建器,该构建器旨在帮助为类似集合的结构创建 fmt::Debug
实现。
Examples
use std::fmt;
struct Foo(Vec<i32>);
impl fmt::Debug for Foo {
fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt.debug_set().entries(self.0.iter()).finish()
}
}
assert_eq!(format!("{:?}", Foo(vec![10, 11])), "{10, 11}");
Run在这个更复杂的示例中,我们使用 format_args!
和 .debug_set()
来构建匹配分支的列表:
use std::fmt;
struct Arm<'a, L, R>(&'a (L, R));
struct Table<'a, K, V>(&'a [(K, V)], V);
impl<'a, L, R> fmt::Debug for Arm<'a, L, R>
where
L: 'a + fmt::Debug, R: 'a + fmt::Debug
{
fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
L::fmt(&(self.0).0, fmt)?;
fmt.write_str(" => ")?;
R::fmt(&(self.0).1, fmt)
}
}
impl<'a, K, V> fmt::Debug for Table<'a, K, V>
where
K: 'a + fmt::Debug, V: 'a + fmt::Debug
{
fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt.debug_set()
.entries(self.0.iter().map(Arm))
.entry(&Arm(&(format_args!("_"), &self.1)))
.finish()
}
}
Run1.2.0 · sourcepub fn debug_map<'b>(&'b mut self) -> DebugMap<'b, 'a>
pub fn debug_map<'b>(&'b mut self) -> DebugMap<'b, 'a>
创建一个 DebugMap
构建器,该构建器旨在帮助为类似 map 的结构创建 fmt::Debug
实现。
Examples
use std::fmt;
struct Foo(Vec<(String, i32)>);
impl fmt::Debug for Foo {
fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt.debug_map().entries(self.0.iter().map(|&(ref k, ref v)| (k, v))).finish()
}
}
assert_eq!(
format!("{:?}", Foo(vec![("A".to_string(), 10), ("B".to_string(), 11)])),
r#"{"A": 10, "B": 11}"#
);
Run