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

Whats painful:

1. Extra indentation for both cases, instead of shoving only the error case aside. 2. How do you annotate the error with details of the current function? In go you can write `return fmt.Errorf("parsing point (id=%v): %w", id, err)` and easily add crucial context for devs to understand why an error occurred. This seems harder to do in rust.

Calling that a strict improvement is too black and white, and the point of my asking others to name good things about Go is to force a more nuanced conversation.




1. You can use that style as well. You're free to return early in the error arm of the match, and make use of the Ok value in later straight line code. I've done that in fallible_function in this example:

    fn main() {
        // prints "first call worked"
        if let Ok(i) = fallible_function(Ok(1)) {
            println!("first call worked");
            
        }
    
        // prints "second call failed: FallibleError("error!")"
        if let Err(e) = fallible_function(Err("error!".to_string())) {
            println!("second call failed: {:?}",e);
        }
    
    }

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

    fn fallible_function(x: Result<i32, String>) -> Result<i32, FallibleError> {
        let y = match x {
            Err(s) => { return Err(FallibleError(s)); },
            Ok(i) => i,
        };
    
        // y now contains the i that was in the Ok.
        // do straight line code with y here
    
        Ok(y)
    }
2. You can create custom errors for a specific function, and put any data that you would have passed to Errorf inside. This way you get the ability to introspect errors to see what went wrong programmatically, and all that data is available for later inspection. Note that we could also have returned a formatted string on error instead of FallibleError exactly like in Go if we wanted to.

Of course, the way you'd write fallible_function if you weren't going out of your way to be verbose would be like this:

    fn fallible_function(x: Result<i32, String>) -> Result<i32, FallibleError> {
        let y = x.map_err(|s| FallibleError(s) )?;
        // y now contains the i that was in the Ok.
        // do straight line code with y here
    
        Ok(y)
    }
Separately, the point of all this is to be able to statically know whether a function can fail or not. We know for a fact that fallible_function can fail. If we write a function

    fn f(x: i32) -> i32 { .. }
We know for a fact it won't fail (unless it panics, but well behaved code should never panic). We don't even have to worry about the possibility of nils getting in there and screwing us up.




Consider applying for YC's Spring batch! Applications are open till Feb 11.

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

Search: