DEV Community

BuyMyMojo
BuyMyMojo

Posted on

Go and Rust error handling

In Go when you run a lot of things it returns an error variable for you to take care of or disregard to handle all of your stuff.

err, otherVariable := someFunction()
if err != Nil {
  // something
}
Enter fullscreen mode Exit fullscreen mode

But in rust it has throwing an exception built in with .except() which is kinda basic but interesting and a lot cleaner looking for larger bits of code

let token = env::var("TESTING_DISCORD_TOKEN")
        .expect("Expected a token in the environment");
Enter fullscreen mode Exit fullscreen mode

So this prints out "Expected a token in the environment" if it errors out so kinda nice.

There is defiantly better ways of handling errors in both languages but this is just a perspective from a beginner in both

Top comments (3)

Collapse
 
chayimfriedman2 profile image
Chayim Friedman

.expect() (or .unwrap()) are not error handling mechanisms, and certainly not equivalent to if err != nil in Go. The usual error handling mechanism in Rust is the ? operators, that has the same meaning as if err == nil { return; }.

Collapse
 
buymymojo profile image
BuyMyMojo

Would that be done like this?:

if let Err(Reason) = somefunc() {
 // handle error?
}
Enter fullscreen mode Exit fullscreen mode
Collapse
 
chayimfriedman2 profile image
Chayim Friedman

Or match.