Skip to content

Adding examples for deriving Debug and Display. #424

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 2 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions ci/dictionary.txt
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ AlphaNumeric
ApiResponse
Appender
appender
armv
args
ascii
ashley
Expand Down Expand Up @@ -80,6 +81,7 @@ dotfiles
DynamicImage
endian
endif
enum
EnvLogger
EnvVar
eprintln
Expand All @@ -91,6 +93,7 @@ filename
filenames
filepath
filesystem
FileType
FilterType
FixedOffset
flate
Expand Down Expand Up @@ -153,6 +156,7 @@ JSON
Json
json
julia
KeyPress
lang
LevelFilter
libhello
Expand Down Expand Up @@ -191,6 +195,7 @@ NotFound
NulError
OAuth
oneline
PageLoad
ParallelIterator
parallelized
params
Expand Down Expand Up @@ -315,6 +320,7 @@ vreq
WalkDir
Walkdir
walkdir
WebEvent
webpage
webservice
whitespace
Expand Down
107 changes: 107 additions & 0 deletions src/basics.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@
| [Generate random values of a custom type][ex-rand-custom] | [![rand-badge]][rand] | [![cat-science-badge]][cat-science] |
| [Create random passwords from a set of alphanumeric characters][ex-rand-passwd] | [![rand-badge]][rand] | [![cat-os-badge]][cat-os] |
| [Create random passwords from a set of user-defined characters][ex-rand-choose] | [![rand-badge]][rand] | [![cat-os-badge]][cat-os] |
| [Implement Debug for a custom type][ex-impl-debug] | [![std-badge]][std] | [![cat-os-badge]][cat] |
| [Implement Display for a custom type][ex-impl-display] | [![std-badge]][std] | [![cat-os-badge]][cat-os] |
| [Run an external command and process stdout][ex-parse-subprocess-output] | [![regex-badge]][regex] | [![cat-os-badge]][cat-os] [![cat-text-processing-badge]][cat-text-processing] |
| [Run an external command passing it stdin and check for an error code][ex-parse-subprocess-input] | [![regex-badge]][regex] | [![cat-os-badge]][cat-os] [![cat-text-processing-badge]][cat-text-processing] |
| [Run piped external commands][ex-run-piped-external-commands] | [![std-badge]][std] | [![cat-os-badge]][cat-os] |
Expand Down Expand Up @@ -1770,6 +1772,110 @@ fn run() -> Result<()> {
# quick_main!(run);
```

[ex-impl-debug]: #ex-impl-debug
<a name="ex-impl-debug"></a>
## Implementing Debug for a custom type

[![std-badge]][std] [![cat-os-badge]][cat-os]

Manually implements the [`Debug`] trait for a custom enum and it's attributes.

```rust
use std::fmt;

enum FileType {
Image {
format: String,
width: i32,
height: i32,
},
Text {
format: String,
},
Binary {
arch: String,
},
}

impl fmt::Debug for FileType {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
FileType::Image {
format,
width,
height,
} => write!(
f,
"Image {{ format: {}, width: {}, height: {} }}",
format, width, height
),
FileType::Text { format } => write!(f, "Text {{ format: {} }}", format),
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We actually don't need to manually write out the Text { format: value } struct-like format here. There are methods on the fmt::Formatter like debug_struct that will do this for us and keep it consistent with what you get from #[derive(Debug)].

FileType::Binary { arch } => write!(f, "Binary {{ arch: {} }}", arch),
}
}
}

fn main() {
let i = FileType::Image {
format: "jpg".to_string(),
width: 10,
height: 10,
};
println!("The FileType is: {:?}", i);

let t = FileType::Text {
format: "csv".to_string(),
};
println!("The FileType is: {:?}", t);

let b = FileType::Binary {
arch: "armv6".to_string(),
};
println!("The FileType is: {:?}", b);
}
```


[ex-impl-display]: #ex-impl-display
<a name="ex-impl-display"></a>
## Implementing Display for a custom type

[![std-badge]][std] [![cat-os-badge]][cat-os]

Manually implements the [`Display`] trait for a custom enum and it's attributes.

```rust
use std::fmt;

enum WebEvent {
PageLoad,
KeyPress(char),
Click { x: i64, y: i64 },
}

impl fmt::Display for WebEvent {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
WebEvent::PageLoad => write!(f, "PageLoad"),
WebEvent::KeyPress(c) => write!(f, "KeyPress({})", c),
WebEvent::Click { x, y } => write!(f, "Click(x: {}, y: {})", x, y),
}
}
}

fn main() {
let l = WebEvent::PageLoad;
println!("The WebEvent is: {}", l);

let k = WebEvent::KeyPress('K');
println!("The WebEvent is: {}", k);

let c = WebEvent::Click { x: 4, y: 9 };
println!("The WebEvent is: {}", c);
}
```


{{#include links.md}}

<!-- API Reference -->
Expand All @@ -1796,6 +1902,7 @@ fn run() -> Result<()> {
[`DateTime::to_rfc2822`]: https://docs.rs/chrono/*/chrono/struct.DateTime.html#method.to_rfc2822
[`DateTime::to_rfc3339`]: https://docs.rs/chrono/*/chrono/struct.DateTime.html#method.to_rfc3339
[`DateTime`]: https://docs.rs/chrono/*/chrono/struct.DateTime.html
[`Debug`]: https://doc.rust-lang.org/std/fmt/trait.Debug.html
[`digest::Context`]: https://briansmith.org/rustdoc/ring/digest/struct.Context.html
[`digest::Digest`]: https://briansmith.org/rustdoc/ring/digest/struct.Digest.html
[`DirEntry::path`]: https://doc.rust-lang.org/std/fs/struct.DirEntry.html#method.path
Expand Down
4 changes: 4 additions & 0 deletions src/intro.md
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,8 @@ community. It needs and welcomes help. For details see
| [Create random passwords from a set of user-defined characters][ex-rand-choose] | [![rand-badge]][rand] | [![cat-os-badge]][cat-os] |
| [Run an external command and process stdout][ex-parse-subprocess-output] | [![regex-badge]][regex] | [![cat-os-badge]][cat-os] [![cat-text-processing-badge]][cat-text-processing] |
| [Run an external command passing it stdin and check for an error code][ex-parse-subprocess-input] | [![std-badge]][std] | [![cat-os-badge]][cat-os] |
| [Implement Debug for a custom type][ex-impl-debug] | [![std-badge]][std] | [![cat-os-badge]][cat-os] |
| [Implement Display for a custom type][ex-impl-display] | [![std-badge]][std] | [![cat-os-badge]][cat-os] |
| [Run piped external commands][ex-run-piped-external-commands] | [![std-badge]][std] | [![cat-os-badge]][cat-os] |
| [Redirect both stdout and stderr of child process to the same file][ex-redirect-stdout-stderr-same-file] | [![std-badge]][std] | [![cat-os-badge]][cat-os] |
| [Continuously process child process' outputs][ex-continuous-process-output] | [![std-badge]][std] | [![cat-os-badge]][cat-os][![cat-text-processing-badge]][cat-text-processing] |
Expand Down Expand Up @@ -204,6 +206,8 @@ community. It needs and welcomes help. For details see
[ex-global-mut-state]: basics.html#ex-global-mut-state
[ex-hex-encode-decode]: encoding.html#ex-hex-encode-decode
[ex-hmac]: basics.html#ex-hmac
[ex-impl-debug]: basics.html#ex-impl-debug
[ex-impl-display]: basics.html#ex-impl-display
[ex-invalid-csv]: encoding.html#ex-invalid-csv
[ex-json-value]: encoding.html#ex-json-value
[ex-lazy-constant]: basics.html#ex-lazy-constant
Expand Down