Hacker News new | past | comments | ask | show | jobs | submit login

Because I'm on my soapbox, I'll also recommend implementing ToString[1] right off the bat, too. That way you can print out useful error messages immediately.

For example, if your errors are:

  enum RispError {
      /// Syntax error returning line number and char
      SyntaxErr(u32, u32),
      /// Parens not balanced; contains number of parens needed
You can impl ToString straight away:

  impl ToString for RispErr {
      fn to_string(&self) -> String {
          match self {
              RispErr::SyntaxErr(l,c) => format!("syntax error at line {}, col {}", l, c),
              RispErr::UnbalancedParens(n) => format!("use your % key more! add {} more paren", n),
Then, when handling the error, you can

  match do_thing() {
      Ok(v) => { ... },
      Err(e) => { // TODO handle error
where do_thing's signature looks like

  fn do_thing(...) -> Result<T, RispErr>;
It takes the same amount of code, but all your error messages are in the same place, you haven't lost information about them, and refactoring to handle them becomes super easy.

(n.b. I dashed this comment off without actually compiling the above, so please forgive any dumb errors =] )

[1] https://doc.rust-lang.org/std/string/trait.ToString.html

Instead of implementing `ToString` directly, you should implement `Display`. A `ToString` implementation will automatically be added, and you get all the formatting goodness out of the box.

That's a good idea! I don't often impl Display so it didn't even occur to me.

As a Lisp programmer, the way most other languages handle errors make me cringe. How could I even make a decent ice cream sundae without error recovery? But I do enjoy that 'make a Lisp' is a like a sport in every other language.



Oof, I love this — thank you thenewwazoo!

I gotta get to sleep, but will either update the post or add a note in the morning.

And of course, will do this in all future rust projects :D

Glad to help! I am a huge huge fan of Rust. I'm almost always hanging out on ##rust and ##rust-beginners on Freenode if you want to ask questions synchronously. :)

Use the "?" operator. That way, you only handle errors one time (probably at the root of your program).

See here: https://github.com/omarabid/rust-starter/blob/master/src/mai...

included this as a note in the essay. I think a quick blog post about this approach would be quite useful actually, if you're up for it thenewwazoo!

Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact