Day 4 is upon us! (and some thoughts about error handing) #5
Replies: 5 comments 3 replies
-
|
My solution for day 4 🦀 ❤️ |
Beta Was this translation helpful? Give feedback.
-
|
Here is my Day 4 Part 1 solution. I will find some time later this week to complete Part 2 as well. I was able to add
|
Beta Was this translation helpful? Give feedback.
-
|
My solution to day 4 part 1. Found this one tough! Tried a lot of different ways until one worked. Thought about using ndarray but couldn't find clear documentation. Included testing/docstrings as per advice from @CarolineMorton and custom error handling. Adapted the custom error handling from @hollygrimm's solution to help me learn - hope you don't mind!! Will try to come back to part 2 later. |
Beta Was this translation helpful? Give feedback.
-
|
My solution for the day 4. This time the first part was more complicated than the second one 😅 |
Beta Was this translation helpful? Give feedback.
-
|
Found the words but could not find correct amount of 'X' shapes. Here is Part 1 of Day 4 as I have not been able to figure out Part 2! |
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
-
🎅 Day 4 - Let's Talk About Error Handling! 🎄
I've been reviewing some of the solutions from the previous days, and I wanted to take a moment to discuss something that can really improve your Rust code: proper error handling! While
unwrap(),expect(), andpanic!are tempting (especially during coding challenges), this is a good opportunity to practice using a more robust approach -Result.Why
Resultoverunwrap/panic?When we use
unwrap()orpanic!, we're essentially saying "crash the program if something goes wrong." While this might be fine for quick scripts, it's not ideal for:Here's a quick example of a common pattern I've seen, with a change to using
Result.Custom Error Types
For bonus points, consider defining your own error types. This makes your code more expressive, and customisable to the problem you are trying to solve. It helps users of your code handle specific error cases:
The ? Operator is Your Friend here
The
?operator is perfect for propagating errors up the call stack. It's more concise thanmatchorif letexpressions and makes your code more readable. It means that an error can bubble up and declare itself.In this example, our function
process_datareturns either a number or aAdventOfCodeError. That error can come from either of the functions that are called inprocess_data:parse_inputandcalculate_result. We are using the?operator here so say if you get an error in those functions, just pass the error up the call stack and return as an error from theprocess_datafunction.Happy coding, and looking forward to seeing your Day 4 solutions! 🎄✨
P.S. If you want to see this in action, check out the documentation for std::result and error handling in the Rust book.
Beta Was this translation helpful? Give feedback.
All reactions