Summary

The Debug trait is intended to be implemented

実装する
by every type and display useful runtime information to help with debugging. This RFC proposes two additions
追加
to the fmt API, one of which aids implementors of Debug, and one which aids consumers of the output of Debug. Specifically,
特に
the # format specifier modifier will cause
起こす
Debug output to be "pretty printed", and some utility builder types will be added
たす
to the std::fmt module to make it easier to implement
実装する
Debug manually.

Motivation

Pretty printing

The conventions for Debug format state that output should resemble Rust struct

構造、構造体
syntax,
文法
without added
たす
line breaks. This can make output difficult to read in the presense of complex
複素数、複文の
and deeply nested
入れ子
structures:

#![allow(unused)] fn main() { HashMap { "foo": ComplexType { thing: Some(BufferedReader { reader: FileStream { path: "/home/sfackler/rust/README.md", mode: R }, buffer: 1013/65536 }), other_thing: 100 }, "bar": ComplexType { thing: Some(BufferedReader { reader: FileStream { path: "/tmp/foobar", mode: R }, buffer: 0/65536 }), other_thing: 0 } } }

This can be made more readable by adding

たす
appropriate indentation:

#![allow(unused)] fn main() { HashMap { "foo": ComplexType { thing: Some( BufferedReader { reader: FileStream { path: "/home/sfackler/rust/README.md", mode: R }, buffer: 1013/65536 } ), other_thing: 100 }, "bar": ComplexType { thing: Some( BufferedReader { reader: FileStream { path: "/tmp/foobar", mode: R }, buffer: 0/65536 } ), other_thing: 0 } } }

However, we wouldn't want this "pretty printed" version to be used by default, since it's significantly

著しく
more verbose.

Helper types

For many Rust types, a Debug implementation

実装
can be automatically
自動的に
generated
生成する
by #[derive(Debug)]. However, many encapsulated types cannot use the derived implementation.
実装
For example, the types in std::io::buffered all have manual
マニュアル、手動
Debug impls. They all maintain a byte buffer that is both extremely large (64k by default) and full of uninitialized
未初期化の
memory. Printing it in the Debug impl would be a terrible idea. Instead, the implementation
実装
prints the size of the buffer as well as how much data is in it at the moment: https://github.com/rust-lang/rust/blob/0aec4db1c09574da2f30e3844de6d252d79d4939/src/libstd/io/buffered.rs#L48-L60

#![allow(unused)] fn main() { pub struct BufferedStream<S> { inner: BufferedReader<InternalBufferedWriter<S>> } impl<S> fmt::Debug for BufferedStream<S> where S: fmt::Debug { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { let reader = &self.inner; let writer = &self.inner.inner.0; write!(fmt, "BufferedStream {{ stream: {:?}, write_buffer: {}/{}, read_buffer: {}/{} }}", writer.inner, writer.pos, writer.buf.len(), reader.cap - reader.pos, reader.buf.len()) } } }

A purely manual

マニュアル、手動
implementation
実装
is tedious to write and error prone. These difficulties become even more pronounced with the introduction
はじめに、導入
of the "pretty printed" format described
記述する
above. If Debug is too painful to manually implement,
実装する
developers of libraries will create poor implementations
実装
or omit
省略する
them entirely. Some simple structures to automatically
自動的に
create the correct output format can significantly
著しく
help ease these implementations:
実装

#![allow(unused)] fn main() { impl<S> fmt::Debug for BufferedStream<S> where S: fmt::Debug { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { let reader = &self.inner; let writer = &self.inner.inner.0; fmt.debug_struct("BufferedStream") .field("stream", writer.inner) .field("write_buffer", &format_args!("{}/{}", writer.pos, writer.buf.len())) .field("read_buffer", &format_args!("{}/{}", reader.cap - reader.pos, reader.buf.len())) .finish() } } }

Detailed design
設計(する)

Pretty printing

The # modifier (e.g. {:#?}) will be interpreted

解釈する
by Debug implementations
実装
as a request for "pretty printed" output:

  • Non-compound output is unchanged from normal Debug output: e.g. 10, "hi", None.
  • Array,
    配列
    set
    セットする、集合
    and map output is printed with one element
    要素
    per line, indented four spaces, and entries
    項目
    printed with the # modifier as well: e.g.
#![allow(unused)] fn main() { [ "a", "b", "c" ] }
#![allow(unused)] fn main() { HashSet { "a", "b", "c" } }
#![allow(unused)] fn main() { HashMap { "a": 1, "b": 2, "c": 3 } }
  • Struct
    構造、構造体
    and tuple
    タプル(複合型)
    struct
    構造、構造体
    output is printed with one field per line, indented four spaces, and fields printed with the # modifier as well: e.g.
#![allow(unused)] fn main() { Foo { field1: "hi", field2: 10, field3: false } }
#![allow(unused)] fn main() { Foo( "hi", 10, false ) }

In all cases, pretty printed and non-pretty printed output should differ only in the addition

追加
of newlines
改行
and whitespace.

Helper types

Types will be added

たす
to std::fmt corresponding
照応する
to each of the common Debug output formats. They will provide a builder-like API to create correctly formatted output, respecting the # flag as needed. A full implementation
実装
can be found at https://gist.github.com/sfackler/6d6610c5d9e271146d11. (Note that there's a lot of almost-but-not-quite duplicated code in the various
さまざまな
impls. It can probably be cleaned up a bit). For convenience, methods will be added
たす
to Formatter which create them. An example of use of the debug_struct method is shown in the Motivation section.
In addition,
追加
the padded method returns a type implementing fmt::Writer that pads input passed to it. This is used inside of the other builders, but is provided
与える
here for use by Debug implementations
実装
that require formats not provided
与える
with the other helpers.

#![allow(unused)] fn main() { impl Formatter { pub fn debug_struct<'a>(&'a mut self, name: &str) -> DebugStruct<'a> { ... } pub fn debug_tuple<'a>(&'a mut self, name: &str) -> DebugTuple<'a> { ... } pub fn debug_set<'a>(&'a mut self, name: &str) -> DebugSet<'a> { ... } pub fn debug_map<'a>(&'a mut self, name: &str) -> DebugMap<'a> { ... } pub fn padded<'a>(&'a mut self) -> PaddedWriter<'a> { ... } } }

Drawbacks

The use of the # modifier adds complexity to Debug implementations.

実装

The builder types are adding

たす
extra #[stable] surface area to the standard library that will have to be maintained.

Alternatives

We could take

とる
the helper structs
構造、構造体
alone without the pretty printing format. They're still useful even if a library author doesn't have to worry about the second format.

Unresolved questions

The indentation level is currently hardcoded to 4 spaces. We could allow

許可する、可能にする
that to be configured as well by using the width or precision
精度
specifiers, for example, {:2#?} would pretty print with a 2-space indent. It's not totally clear to me that this provides
与える
enough value to justify the extra complexity.