Why does Goland color `err` differently?

Viewed 399

I have this code in Go:

func Provision(env string) error {
    primaryPath, err := FindPrimaryRegionForEnv(env)
    if err != nil {
        return err
    }
    region := extractRegionFromEnvPath(env, primaryPath)
    if err = ProvisionTableInDynamoDB(env, region); err != nil {
        return err
    }
    return nil
}

Which Goland colors like this:

enter image description here

When I change if err = ... to if err := ... then the color of err changes:

enter image description here

What does the greenish err mean?

1 Answers

It boils down to how shadow variables work in pretty much all type-safe languages. In this case, green err mean that you're redeclaring the variable rather than changing its value.

The reason why Goland bothered to highlight is this is that within the scope of the redeclaration you may get a value/type that contradicts the shadow declaration.

package main

import (
    "errors"
    "fmt"
    "reflect"
)

func boolErrType() bool {
    return false
}

func errType() error {
    return errors.New("this is an error")
}

func main() {
    err := boolErrType()
    if !err {
        fmt.Printf("Within boolErrType if condition: %s\n", reflect.TypeOf(err).String())
    }

    if err := errType(); err != nil {
        fmt.Printf("Within errType if condition: %s\n", reflect.TypeOf(err).String())
    }

    fmt.Printf("Within main function: %s\n", reflect.TypeOf(err).String())
}

https://go.dev/play/p/IwDb7iBZYc2

In this example you've two different behaviours, the err will be a boolean type within the main block. Except for when it's in the if condition scope, it will be given an error type.

This is mainly affected when you've started using shadow variables outside of the error scenarios as you could be for example pass an incorrect pointer to a function that causes an unexpected error. Go compiler will have a hard time tracking these shadow variables and won't always catch them at build time.

This could leave unexpected/unknown bugs in your production applications that user's then will be able to exploit.

Here's an article about this that might be useful as well. https://nidhi-ag.medium.com/variable-shadowing-in-golang-f500e8e58931

Related