DEV Community

Charles Scholle
Charles Scholle

Posted on

4

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
}
Enter fullscreen mode Exit fullscreen mode

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
}
Enter fullscreen mode Exit fullscreen mode

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

Hostinger image

Get n8n VPS hosting 3x cheaper than a cloud solution

Get fast, easy, secure n8n VPS hosting from $4.99/mo at Hostinger. Automate any workflow using a pre-installed n8n application and no-code customization.

Start now

Top comments (0)

AWS GenAI LIVE image

How is generative AI increasing efficiency?

Join AWS GenAI LIVE! to find out how gen AI is reshaping productivity, streamlining processes, and driving innovation.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay