Skip to content

Commit 8a6f60d

Browse files
authored
Mention {:#?} formatting
In the chapter on JSON parsing, you introduce the `Debug`. I propose you also introduce the 'alternate'/pretty-printed form `{:#?}` which renders much more readable output. The new output was actually generated like this: https://is.gd/QahSp0
1 parent 098db7c commit 8a6f60d

File tree

1 file changed

+30
-1
lines changed

1 file changed

+30
-1
lines changed

parse-json/README.md

Lines changed: 30 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -196,11 +196,40 @@ Run it now and you should see this:
196196
```bash
197197
$ cargo run -q
198198
Result is:
199-
[Repository { name: "ajv", description: "The fastest JSON schema Validator. Supports v5 proposals", fork: true }, Repository { name: "angular", description: "Code to optimize AngularJS for complex pages", fork: true },...
199+
[Repository { name: "ajv", description: "The fastest JSON schema Validator. Supports v5 proposals", fork: true }, Repository { name: "angular", description: "Code to optimize AngularJS for complex pages", fork: true }, ...]
200200
```
201201
202202
You see that our `Vec<Repository>` is printed with `{:?}` in the format `[Repository { name, description, fork }, ...]`. Thanks to `#[derive(Debug)]`!
203203

204+
But that is not all: The [string formatting](https://doc.rust-lang.org/nightly/std/fmt/index.html) in Rust allow you to do a bunch of really cool things, e.g., padding inputs to a certain length or choosing representations for numbers. One of the most amazing features is the "alternate mode", which you can trigger with an `#`. The alternate mode for `Debug` is to pretty-print the data, so it gets split up in lines and is nicely indented!
205+
206+
If we change our `println` to
207+
208+
```rust
209+
println!("Result is:\n{:#?}", repositories);
210+
// ^-- added a `#` here
211+
```
212+
213+
it will now output our data like this:
214+
215+
```bash
216+
$ cargo run -q
217+
Result is:
218+
[
219+
Repository {
220+
name: "ajv",
221+
description: "The fastest JSON schema Validator. Supports v5 proposals",
222+
fork: true
223+
},
224+
Repository {
225+
name: "angular",
226+
description: "Code to optimize AngularJS for complex pages",
227+
fork: true
228+
},
229+
...
230+
]
231+
```
232+
204233
Phew. A lot of new concepts and unstable features to parse JSON in an ergonomic way. But it _is_ ergonomic and powerful, if you use these features.
205234
206235
I guess as a JavaScript developers you just need to get comfortable to move more work to the Rust compiler, so you can work more declarative using attributes in Rust.

0 commit comments

Comments
 (0)