pub struct Formatter<'a> {/* private fields */ }Expand description
Configuration for formatting.
AFormatter represents various options related to formatting. Users do notconstructFormatters directly; a mutable reference to one is passed tothefmt method of all formatting traits, likeDebug andDisplay.
To interact with aFormatter, you’ll call various methods to change thevarious options related to formatting. For examples, please see thedocumentation of the methods defined onFormatter below.
Implementations§
Source§impl<'a>Formatter<'a>
impl<'a>Formatter<'a>
Sourcepub const fnnew( write: &'a mut (dynWrite + 'a), options:FormattingOptions,) -> Self
🔬This is a nightly-only experimental API. (formatting_options #118117)
pub const fnnew( write: &'a mut (dynWrite + 'a), options:FormattingOptions,) -> Self
formatting_options #118117)Creates a new formatter with givenFormattingOptions.
Ifwrite is a reference to a formatter, it is recommended to useFormatter::with_options instead as this can borrow the underlyingwrite, thereby bypassing one layer of indirection.
You may alternatively useFormattingOptions::create_formatter().
Sourcepub const fnwith_options<'b>( &'b mut self, options:FormattingOptions,) ->Formatter<'b>
🔬This is a nightly-only experimental API. (formatting_options #118117)
pub const fnwith_options<'b>( &'b mut self, options:FormattingOptions,) ->Formatter<'b>
formatting_options #118117)Creates a new formatter based on this one with givenFormattingOptions.
Source§impl<'a>Formatter<'a>
impl<'a>Formatter<'a>
1.0.0 ·Sourcepub fnpad_integral( &mut self, is_nonnegative:bool, prefix: &str, buf: &str,) ->Result
pub fnpad_integral( &mut self, is_nonnegative:bool, prefix: &str, buf: &str,) ->Result
Performs the correct padding for an integer which has already beenemitted into a str. The str shouldnot contain the sign for theinteger, that will be added by this method.
§Arguments
- is_nonnegative - whether the original integer was either positive or zero.
- prefix - if the ‘#’ character (Alternate) is provided, thisis the prefix to put in front of the number.
- buf - the byte array that the number has been formatted into
This function will correctly account for the flags provided as well asthe minimum width. It will not take precision into account.
§Examples
usestd::fmt;structFoo { nb: i32 }implFoo {fnnew(nb: i32) -> Foo { Foo { nb, } }}implfmt::DisplayforFoo {fnfmt(&self, formatter:&mutfmt::Formatter<'_>) -> fmt::Result {// We need to remove "-" from the number output.lettmp =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");1.0.0 ·Sourcepub fnpad(&mut self, s: &str) ->Result
pub fnpad(&mut self, s: &str) ->Result
Takes a string slice and emits it to the internal buffer after applyingthe relevant formatting flags specified.
The flags recognized for generic strings are:
- width - the minimum width of what to emit
- fill/align - what to emit and where to emit it if the stringprovided needs to be padded
- precision - the maximum length to emit, the string is truncated if itis longer than this length
Notably this function ignores theflag parameters.
§Examples
1.0.0 ·Sourcepub fnwrite_str(&mut self, data: &str) ->Result
pub fnwrite_str(&mut self, data: &str) ->Result
Writes some data to the underlying buffer contained within thisformatter.
§Examples
1.0.0 ·Sourcepub fnwrite_fmt(&mut self, fmt:Arguments<'_>) ->Result
pub fnwrite_fmt(&mut self, fmt:Arguments<'_>) ->Result
1.0.0 ·Sourcepub fnflags(&self) ->u32
👎Deprecated since 1.24.0: use thesign_plus,sign_minus,alternate, orsign_aware_zero_pad methods instead
pub fnflags(&self) ->u32
sign_plus,sign_minus,alternate, orsign_aware_zero_pad methods insteadReturns flags for formatting.
1.5.0 ·Sourcepub fnfill(&self) ->char
pub fnfill(&self) ->char
Returns the character used as ‘fill’ whenever there is alignment.
§Examples
usestd::fmt;structFoo;implfmt::DisplayforFoo {fnfmt(&self, formatter:&mutfmt::Formatter<'_>) -> fmt::Result {letc = formatter.fill();if letSome(width) = formatter.width() {for _ in0..width {write!(formatter,"{c}")?; }Ok(()) }else{write!(formatter,"{c}") } }}// We set alignment to the right with ">".assert_eq!(format!("{Foo:G>3}"),"GGG");assert_eq!(format!("{Foo:t>6}"),"tttttt");1.28.0 ·Sourcepub fnalign(&self) ->Option<Alignment>
pub fnalign(&self) ->Option<Alignment>
Returns a flag indicating what form of alignment was requested.
§Examples
usestd::fmt::{self, Alignment};structFoo;implfmt::DisplayforFoo {fnfmt(&self, formatter:&mutfmt::Formatter<'_>) -> fmt::Result {lets =if letSome(s) = formatter.align() {matchs { 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");1.5.0 ·Sourcepub fnwidth(&self) ->Option<usize>
pub fnwidth(&self) ->Option<usize>
Returns the optionally specified integer width that the output should be.
§Examples
usestd::fmt;structFoo(i32);implfmt::DisplayforFoo {fnfmt(&self, formatter:&mutfmt::Formatter<'_>) -> fmt::Result {if letSome(width) = formatter.width() {// If we received a width, we use itwrite!(formatter,"{:width$}",format!("Foo({})",self.0), width = width) }else{// Otherwise we do nothing specialwrite!(formatter,"Foo({})",self.0) } }}assert_eq!(format!("{:10}", Foo(23)),"Foo(23) ");assert_eq!(format!("{}", Foo(23)),"Foo(23)");1.5.0 ·Sourcepub fnprecision(&self) ->Option<usize>
pub fnprecision(&self) ->Option<usize>
Returns the optionally specified precision for numeric types.Alternatively, the maximum width for string types.
§Examples
usestd::fmt;structFoo(f32);implfmt::DisplayforFoo {fnfmt(&self, formatter:&mutfmt::Formatter<'_>) -> fmt::Result {if letSome(precision) = formatter.precision() {// If we received a precision, we use it.write!(formatter,"Foo({1:.*})", precision,self.0) }else{// Otherwise we default to 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)");1.5.0 ·Sourcepub fnsign_plus(&self) ->bool
pub fnsign_plus(&self) ->bool
Determines if the+ flag was specified.
§Examples
usestd::fmt;structFoo(i32);implfmt::DisplayforFoo {fnfmt(&self, formatter:&mutfmt::Formatter<'_>) -> fmt::Result {ifformatter.sign_plus() {write!(formatter,"Foo({}{})",ifself.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)");1.5.0 ·Sourcepub fnsign_minus(&self) ->bool
pub fnsign_minus(&self) ->bool
Determines if the- flag was specified.
§Examples
usestd::fmt;structFoo(i32);implfmt::DisplayforFoo {fnfmt(&self, formatter:&mutfmt::Formatter<'_>) -> fmt::Result {ifformatter.sign_minus() {// You want a minus sign? Have one!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)");1.5.0 ·Sourcepub fnalternate(&self) ->bool
pub fnalternate(&self) ->bool
Determines if the# flag was specified.
§Examples
usestd::fmt;structFoo(i32);implfmt::DisplayforFoo {fnfmt(&self, formatter:&mutfmt::Formatter<'_>) -> fmt::Result {ifformatter.alternate() {write!(formatter,"Foo({})",self.0) }else{write!(formatter,"{}",self.0) } }}assert_eq!(format!("{:#}", Foo(23)),"Foo(23)");assert_eq!(format!("{}", Foo(23)),"23");1.5.0 ·Sourcepub fnsign_aware_zero_pad(&self) ->bool
pub fnsign_aware_zero_pad(&self) ->bool
Determines if the0 flag was specified.
§Examples
usestd::fmt;structFoo(i32);implfmt::DisplayforFoo {fnfmt(&self, formatter:&mutfmt::Formatter<'_>) -> fmt::Result {assert!(formatter.sign_aware_zero_pad());assert_eq!(formatter.width(),Some(4));// We ignore the formatter's options.write!(formatter,"{}",self.0) }}assert_eq!(format!("{:04}", Foo(23)),"23");1.2.0 ·Sourcepub fndebug_struct<'b>(&'b mut self, name: &str) ->DebugStruct<'b, 'a>
pub fndebug_struct<'b>(&'b mut self, name: &str) ->DebugStruct<'b, 'a>
Creates aDebugStruct builder designed to assist with creation offmt::Debug implementations for structs.
§Examples
usestd::fmt;usestd::net::Ipv4Addr;structFoo { bar: i32, baz: String, addr: Ipv4Addr,}implfmt::DebugforFoo {fnfmt(&self, fmt:&mutfmt::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), }));1.2.0 ·Sourcepub fndebug_tuple<'b>(&'b mut self, name: &str) ->DebugTuple<'b, 'a>
pub fndebug_tuple<'b>(&'b mut self, name: &str) ->DebugTuple<'b, 'a>
Creates aDebugTuple builder designed to assist with creation offmt::Debug implementations for tuple structs.
§Examples
usestd::fmt;usestd::marker::PhantomData;structFoo<T>(i32, String, PhantomData<T>);impl<T> fmt::DebugforFoo<T> {fnfmt(&self, fmt:&mutfmt::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>)));1.2.0 ·Sourcepub fndebug_list<'b>(&'b mut self) ->DebugList<'b, 'a>
pub fndebug_list<'b>(&'b mut self) ->DebugList<'b, 'a>
Creates aDebugList builder designed to assist with creation offmt::Debug implementations for list-like structures.
§Examples
1.2.0 ·Sourcepub fndebug_set<'b>(&'b mut self) ->DebugSet<'b, 'a>
pub fndebug_set<'b>(&'b mut self) ->DebugSet<'b, 'a>
Creates aDebugSet builder designed to assist with creation offmt::Debug implementations for set-like structures.
§Examples
usestd::fmt;structFoo(Vec<i32>);implfmt::DebugforFoo {fnfmt(&self, fmt:&mutfmt::Formatter<'_>) -> fmt::Result { fmt.debug_set().entries(self.0.iter()).finish() }}assert_eq!(format!("{:?}", Foo(vec![10,11])),"{10, 11}");In this more complex example, we useformat_args! and.debug_set()to build a list of match arms:
usestd::fmt;structArm<'a, L, R>(&'a(L, R));structTable<'a, K, V>(&'a[(K, V)], V);impl<'a, L, R> fmt::DebugforArm<'a, L, R>whereL:'a+ fmt::Debug, R:'a+ fmt::Debug{fnfmt(&self, fmt:&mutfmt::Formatter<'_>) -> fmt::Result { L::fmt(&(self.0).0, fmt)?; fmt.write_str(" => ")?; R::fmt(&(self.0).1, fmt) }}impl<'a, K, V> fmt::DebugforTable<'a, K, V>whereK:'a+ fmt::Debug, V:'a+ fmt::Debug{fnfmt(&self, fmt:&mutfmt::Formatter<'_>) -> fmt::Result { fmt.debug_set() .entries(self.0.iter().map(Arm)) .entry(&Arm(&(format_args!("_"),&self.1))) .finish() }}1.2.0 ·Sourcepub fndebug_map<'b>(&'b mut self) ->DebugMap<'b, 'a>
pub fndebug_map<'b>(&'b mut self) ->DebugMap<'b, 'a>
Creates aDebugMap builder designed to assist with creation offmt::Debug implementations for map-like structures.
§Examples
usestd::fmt;structFoo(Vec<(String, i32)>);implfmt::DebugforFoo {fnfmt(&self, fmt:&mutfmt::Formatter<'_>) -> fmt::Result { fmt.debug_map().entries(self.0.iter().map(|&(refk,refv)| (k, v))).finish() }}assert_eq!(format!("{:?}", Foo(vec![("A".to_string(),10), ("B".to_string(),11)])),r#"{"A": 10, "B": 11}"#);Sourcepub const fnsign(&self) ->Option<Sign>
🔬This is a nightly-only experimental API. (formatting_options #118117)
pub const fnsign(&self) ->Option<Sign>
formatting_options #118117)Returns the sign of this formatter (+ or-).
Sourcepub const fnoptions(&self) ->FormattingOptions
🔬This is a nightly-only experimental API. (formatting_options #118117)
pub const fnoptions(&self) ->FormattingOptions
formatting_options #118117)Returns the formatting options this formatter corresponds to.