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.
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.
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()
}
}
}
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.
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> { ... }
}
}
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.
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.
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.