Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
November 29, 2022 09:40 pm GMT

Golang: Named Returns Are Useful!!!

Named returns

If you are not familiar with what a named return is, reference A Tour of Go Basics.

Named returns... Hurk...

I know, I know... Named returns can decrease the readability of longer functions written in Golang, but there is a case in which they are a necessity. Handling panics gracefully!

Problem

In many languages, you might use a try/catch block to handle some code that might otherwise throw an exception and wreak havoc. They allow us to override any values. In Golang, we have panics.

First, let's create a simple function that divides 2 integers:

func Divide(numerator, denominator int) (int, error) {    return numerator / denominator, nil}

The issue with this code is that we cannot divide by 0. Doing so will result in: panic: runtime error: integer divide by zero.

We could have a check for whether the denominator is 0, but for the purposes of this post, how can we gracefully handle this panic?

Solution

Here's a refresher on panic, defer, and recover.

By naming the return values, val and err respectively, we can recover from the panic and return any value and error we would like.

func Divide(numerator, denominator int) (val int, err error) {    defer func() {        if r := recover(); r != nil {            err = r.(error)        }    }()    return numerator / denominator, nil}

Now, instead of needing to handle the panic everywhere Divide is called, callers can simply handle the graceful error.


Original Link: https://dev.to/chaz8080/golang-named-returns-are-useful-38ne

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To