Skip to content
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

Day 2 (Advent of Code 2022) #263

Closed
abderrahimAMZ opened this issue Jul 30, 2023 · 1 comment
Closed

Day 2 (Advent of Code 2022) #263

abderrahimAMZ opened this issue Jul 30, 2023 · 1 comment

Comments

@abderrahimAMZ
Copy link

hi fasterthanlime, big fan here! i check your AoC answers to learn from them, i like how you solve them and the explaining is clear. however, i don't get why exactly why not just build the logic directly instead of implementing enums and structs. if you already have a blog, youtube video, explaining the thing, give me the link and don't waste your time.

@fasterthanlime
Copy link
Owner

however, i don't get why exactly why not just build the logic directly instead of implementing enums and structs

So there's several reasons!

One reason to use types is so you remember what a thing is for. Let's say for example you have:

struct Person {
  first_name: String,
  last_name: String,
}

You can accidentally do something like:

person_a.last_name = person_b.first_name;

If instead you used types like:

struct Person {
  first_name: FirstName,
  last_name: LastName,
}

Then the compiler would've caught that. This code for example:

struct FirstName(String);
struct LastName(String);

struct Person {
    first_name: FirstName,
    last_name: LastName,
}

fn main() {
    let person1 = Person {
        first_name: FirstName("John".into()),
        last_name: LastName("Doe".into()),
    };

    let person2 = Person {
        first_name: FirstName("Jane".into()),
        last_name: LastName("Doe".into()),
    };

    person1.last_name = person2.first_name;

    println!("Hello, world!");
}

Gives us this error:

$ cargo c
    Checking whytypes v0.1.0 (/Users/amos/bearcove/whytypes)
error[E0308]: mismatched types
  --> src/main.rs:20:25
   |
20 |     person1.last_name = person2.first_name;
   |     -----------------   ^^^^^^^^^^^^^^^^^^ expected `LastName`, found `FirstName`
   |     |
   |     expected due to the type of this binding

This is a pretty contrived example, of course. But for example, I'd rather receive one of these:

struct Point3 {
  x: f64,
  y: f64,
  z: f64,
}

Than a (f64, f64, f64) or a [f64; 3].


Of course you wouldn't necessarily have to go through intermediate types like I do, but for me it's just how i think about problems. Once you find the right data structure, solving the problem itself becomes trivial.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants