diff --git a/Cargo.lock b/Cargo.lock new file mode 100644 index 0000000..536c324 --- /dev/null +++ b/Cargo.lock @@ -0,0 +1,7 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 3 + +[[package]] +name = "by-example-01-02-01-debug" +version = "0.1.0" diff --git a/src/main.rs b/src/main.rs index e7a11a9..69c1ecb 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,3 +1,43 @@ -fn main() { - println!("Hello, world!"); +#![allow(unused)] + +// This structure cannot be printed either with `fmt::Display` or +// with `fmt::Debug`. +struct UnPrintable(i32); + +// The `derive` attribute automatically creates the implementation +// required to make this `struct` printable with `fmt::Debug`. +#[derive(Debug)] +struct DebugPrintable(i32); + +// Derive the `fmt::Debug` implementation for `Structure`. `Structure` +// is a structure which contains a single `i32`. +#[derive(Debug)] +struct Structure { + x: i32, +} + +// Put a `Structure` inside of the structure `Deep`. Make it printable +// also. +#[derive(Debug)] +struct Deep(Structure); + +fn main() { + // Printing with `{:?}` is similar to with `{}`. + println!("{:?} months in a year.", 12); + println!( + "{1:?} {0:?} is the {actor:?} name.", + "Slater", + "Christian", + actor = "actor's" + ); + + // `Structure` is printable! + println!("Now {:?} will print!", Structure { x: 3 }); + // The problem with `derive` is there is no control over how + // the results look. What if I want this to just show a `7`? + println!("Now {:?} will print!", Deep(Structure { x: 7 })); + + let x = Deep(Structure { x: 7 }); + + println!("{}", x.0.x); }