Struct std::fmt::Formatter1.0.0[][src]

pub struct Formatter<'a> { /* fields omitted */ }
Expand description

格式化配置。

Formatter 代表与格式相关的各种选项。 用户不直接构建 Formatters。将所有格式为 traits 的 fmt 方法 (例如 DebugDisplay) 传递给 fmt 方法。

要与 Formatter 进行交互,您将调用各种方法来更改与格式相关的各种选项。 有关示例,请参见下面在 Formatter 上定义的方法的文档。

Implementations

对已经发出到 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");
Run

应用指定的相关格式设置标志后,此函数将获取一个字符串片段并将其发送到内部缓冲区。 泛型字符串可识别的标志为:

  • 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!("{:<4}", Foo), "Foo ");
assert_eq!(&format!("{:0>4}", Foo), "0Foo");
Run

将一些数据写入此格式化程序中包含的基础缓冲区。

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!("{:0>8}", Foo), "Foo");
Run

将一些格式化的信息写入此实例。

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");
Run
👎 Deprecated since 1.24.0:

use the sign_plus, sign_minus, alternate, or sign_aware_zero_pad methods instead

格式化标志

对齐时用作 ‘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!("{:G>3}", Foo), "GGG");
assert_eq!(&format!("{:t>6}", Foo), "tttttt");
Run

指示请求对齐方式的标志。

Examples

extern crate core;

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");
Run

(可选) 指定输出应为的整数宽度。

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)");
Run

可选地为数字类型指定精度。 或者,为字符串类型的最大宽度。

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)");
Run

确定是否指定了 + 标志。

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)
        } else {
            write!(formatter, "Foo({})", self.0)
        }
    }
}

assert_eq!(&format!("{:+}", Foo(23)), "Foo(+23)");
assert_eq!(&format!("{}", Foo(23)), "Foo(23)");
Run

确定是否指定了 - 标志。

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)");
Run

确定是否指定了 # 标志。

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");
Run

确定是否指定了 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");
Run

创建一个 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),
    })
);
Run

创建一个 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>))
);
Run

创建一个 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]");
Run

创建一个 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: 'a, R: 'a>(&'a (L, R));
struct Table<'a, K: 'a, V: 'a>(&'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()
    }
}
Run

创建一个 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

Trait Implementations

将字符串切片写入此 writer,返回写入是否成功。 Read more

char 写入此 writer,返回写入是否成功。 Read more

结合使用 write! 宏和 trait 的实现者。 Read more

Auto Trait Implementations

Blanket Implementations

获取 selfTypeIdRead more

从拥有的值中一成不变地借用。 Read more

从拥有的值中借用。 Read more

执行转换。

执行转换。

发生转换错误时返回的类型。

执行转换。

发生转换错误时返回的类型。

执行转换。