Skip to content

Problem-first approach #17

Description

@mre

Add screenshots of error messages from other languages

Focus on a "problem-first narrative":

- Debug trait first
- You can use derive for Debug
- This way, they already know what Debug is (a trait)
- Then we can go from there and introduce other traits like Display

Story arch:

"I cannot print my type!"

(because you didn't derive Debug):

```rust
fn main() {
    let first_name = FirstName("John".to_string());
    println!("My name is {:?}", first_name); // doesn't compile because FirstName doesn't implement Debug
}

"But you can implement Debug yourself:"

impl Debug for FirstName {
    // ...
}

"That's a lot of code!"
-> "you can derive Debug and it will do that for you!"

#[derive(Debug)]
struct FirstName(String);

fn main() {
    let first_name = FirstName("John".to_string());
    println!("My name is {:?}", first_name); // now it works!
}

Sometimes it's useful to implement manually.

// deriving Debug here is dangerous, because it would leak the password string
struct Password(String);

// instead...
impl Debug for Password {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "Password(****)")
    }
}

"My code is ugly!"

E.g. missing Display impl:

fn main() {
    // newtype
    let first_name = FirstName("John".to_string());
    // now you can't easily print that anymore!
    // so you have to use .0:
    let name = first_name.0;
    println!("My name is {}", name);
}

"Here's a trait. If you implement that, your code will be better."

impl std::fmt::Display for FirstName {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", self.0)
    }
}

fn main() {
    let first_name = FirstName("John".to_string());
    // now you can easily print that!
    println!("My name is {}", first_name);
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions