Skip to main content
Redhat Developers  Logo
  • Products

    Platforms

    • Red Hat Enterprise Linux
      Red Hat Enterprise Linux Icon
    • Red Hat AI
      Red Hat AI
    • Red Hat OpenShift
      Openshift icon
    • Red Hat Ansible Automation Platform
      Ansible icon
    • View All Red Hat Products

    Featured

    • Red Hat build of OpenJDK
    • Red Hat Developer Hub
    • Red Hat JBoss Enterprise Application Platform
    • Red Hat OpenShift Dev Spaces
    • Red Hat OpenShift Local
    • Red Hat Developer Sandbox

      Try Red Hat products and technologies without setup or configuration fees for 30 days with this shared Openshift and Kubernetes cluster.
    • Try at no cost
  • Technologies

    Featured

    • AI/ML
      AI/ML Icon
    • Linux
      Linux Icon
    • Kubernetes
      Cloud icon
    • Automation
      Automation Icon showing arrows moving in a circle around a gear
    • View All Technologies
    • Programming Languages & Frameworks

      • Java
      • Python
      • JavaScript
    • System Design & Architecture

      • Red Hat architecture and design patterns
      • Microservices
      • Event-Driven Architecture
      • Databases
    • Developer Productivity

      • Developer productivity
      • Developer Tools
      • GitOps
    • Automated Data Processing

      • AI/ML
      • Data Science
      • Apache Kafka on Kubernetes
    • Platform Engineering

      • DevOps
      • DevSecOps
      • Ansible automation for applications and services
    • Secure Development & Architectures

      • Security
      • Secure coding
  • Learn

    Featured

    • Kubernetes & Cloud Native
      Openshift icon
    • Linux
      Rhel icon
    • Automation
      Ansible cloud icon
    • AI/ML
      AI/ML Icon
    • View All Learning Resources

    E-Books

    • GitOps Cookbook
    • Podman in Action
    • Kubernetes Operators
    • The Path to GitOps
    • View All E-books

    Cheat Sheets

    • Linux Commands
    • Bash Commands
    • Git
    • systemd Commands
    • View All Cheat Sheets

    Documentation

    • Product Documentation
    • API Catalog
    • Legacy Documentation
  • Developer Sandbox

    Developer Sandbox

    • Access Red Hat’s products and technologies without setup or configuration, and start developing quicker than ever before with our new, no-cost sandbox environments.
    • Explore Developer Sandbox

    Featured Developer Sandbox activities

    • Get started with your Developer Sandbox
    • OpenShift virtualization and application modernization using the Developer Sandbox
    • Explore all Developer Sandbox activities

    Ready to start developing apps?

    • Try at no cost
  • Blog
  • Events
  • Videos

How to fix issues caused by reusing Go error variables

October 17, 2022
Massimiliano Ziccardi
Related topics:
Go
Related products:
Red Hat Enterprise Linux

Share:

    This article discusses issues caused by reusing error variables in Go code. I will begin by illustrating the problem with a fictional company called ACME Corporation and its software engineer Wile E. Then I will present trivial examples to reveal the problem and how to avoid it.

    The story of a reused Go error variable

    A user opened a new issue to ACME Corporation because he noticed that users could enter any string into the phone number on the contact form. Wile E. is in charge of implementing a fix.

    Wile E. examines the code:

    func StoreAllContacts() {
      for _, c := range contactsToStore {
        err := legacy.StoreContact(&c)
        if err != nil {
          fmt.Printf("Error storing %v: %v\n", c, err)
        } else {
          fmt.Printf("Contact NAME: %s, SURNAME: %s, PHONE: %s stored successfully!\n", c.Name, c.Surname, c.PhoneNumber)
        }
      }
    }

    When he runs the code, he sees the following output:

    Contact NAME: John, SURNAME: Doe, PHONE: (012) 3456789 stored successfully!
    Contact NAME: Jane, SURNAME: Doe, PHONE: (089) 3456789 stored successfully!
    Contact NAME: Tom, SURNAME: Doe, PHONE: (083) 1234567 stored successfully!

    Wile thinks, "OK. Fixing the code should be easy. I will add the check for the phone number format just before calling the StoreContact function."

    Then, Wile produces the following code:

    const phoneNumberRe = `\(\d{3}\) \d{7}`
    
    func validatePhoneNumber(phoneNumber string) (bool, error) {
      re, err := regexp.Compile(phoneNumberRe)
      if err != nil {
        return false, err
      }
      return re.MatchString(phoneNumber), nil
    }
    
    func StoreAllContacts() {
      for _, c := range contactsToStore {
        valid, err := validatePhoneNumber(c.PhoneNumber)
        if err != nil {
          fmt.Printf("Invalid phone number RE ('%s'). Validation ignored.\n", phoneNumberRe)
        }
    
        if !valid {
          fmt.Printf("Invalid phone number '%s' for '%s %s'", c.PhoneNumber, c.Name, c.Surname)
        }
    
        err = legacy.StoreContact(&c)
        if err != nil {
          fmt.Printf("Error storing %v: %v\n", c, err)
        }
      }
    }

    Wile runs the code, but the output is not what he expected:

    Error storing {John Doe (012) 3456789}: <nil>
    Error storing {Jane Doe (089) 3456789}: <nil>
    Error storing {Tom Doe (083) 1234567}: <nil>

    Wile wonders what is happening: "The program enters the if err != nil branch, but then the output of the fmt.Printf shows that err is nil..."

    What makes Wile even more confused is that he didn't change anything inside StoreContact. So he wonders why the behavior changed.

    After some debugging, Wile decides to look at the StoreContact method:

    func StoreContact(c *Contact) *ContactError {
      if err := c.validate(); err != nil {
        return err
      }
    
      // ... store the contact somewhere
      return nil
    }

    Wile: "Oh! There it is!"

    Wile gets permission to fix the function as follows:

    func StoreContact(c *Contact) error {
      if err := c.validate(); err != nil {
        return err
      }
    
      // ... store the contact somewhere
      return nil
    }
    

    When he reruns the code, it finally works as expected. But how did he arrive at this fix?

    The fix explained: The hidden dynamic type

    To understand the issue, let's look at the following code:

    package main
    
    import "fmt"
    
    type MyTestError struct {
    }
    
    func (MyTestError) Error() string {
      return "Test Error String"
    }
    
    func main() {
      var err error // (1)
      fmt.Println("Is err nil?", err == nil)
      var mytesterror *MyTestError // (2)
      fmt.Println("Is mytesterror nil?", mytesterror == nil)
    
      err = mytesterror // (3)
      fmt.Println("Is err nil?", err == nil)
    }
    

    Here are descriptions of the commented-out numbers:

    1. We create a variable of type error. We didn't assign any value to it, so it will be nil.
    2. We create a variable of type *MyTestError. As before, we didn't give any value to it, so it will be nil.
    3. We assign mytesterror (nil) to err. Since mytesterror is nil, should be nil too.

    Let's try to run the code (you can run it at the Go Playground):

    Is err nil? true
    Is mytesterror nil? true
    Is err nil? false

    The reason for this unexpected behavior is that the interface type in Go is composed of a value and a dynamic type. The interface is considered nil only when the value and the type are nil.

    With that in mind, let's look again at the code:

    1. We create a variable of type error. We didn't assign any value to it, so it will be nil.
    2. We create a variable of type *MyTestError. As before, we didn't give any value to it, so it will be nil.
    3. We assign mytesterror (that is, nil) to err. After this assignment, the value of the err interface is nil, but the type is *MyTestError. As explained, an interface with a non-nil type is not nil even if the value is nil.

    To make the issue more evident, let's run the following code:

    package main
    
    import "fmt"
    
    type MyTestError struct {
    }
    
    func (MyTestError) Error() string {
      return "Test Error String"
    }
    
    func main() {
      var err error // (1)
      fmt.Println("Type of err:", reflect.TypeOf(err))
      fmt.Println("Is err nil?", err == nil)
    
      var mytesterror *MyTestError // (2)
      fmt.Println("Type of mytesterror:", reflect.TypeOf(mytesterror))
      fmt.Println("Is mytesterror nil?", mytesterror == nil)
    
      err = mytesterror // (3)
      fmt.Println("Type of err:", reflect.TypeOf(err))
      fmt.Println("Is err nil?", err == nil)
    }

    The output is:

    Type of err: <nil>
    Is err nil? true
    Type of mytesterror: *main.MyTestError
    Is mytesterror nil? true
    Type of err: *main.MyTestError
    Is err nil? false
    

    The assignment changed the type of err from <nil> to *main.MyTestError.

    The same happens with code like this:

    package main
    
    import (
    	"fmt"
    	"reflect"
    )
    
    type MyTestError struct {
    }
    
    func (MyTestError) Error() string {
    	return "Test Error String"
    }
    
    func MyTestFunc() error {
    	var err *MyTestError
    	return err
    }
    
    func main() {
    	err := MyTestFunc()
    	if err != nil {
    		fmt.Println("An error has occurred: ", err)
    		fmt.Println("Type of err: ", reflect.TypeOf(err))
    		return
    	}
    	fmt.Println("Success!")
    }

    If you try to run it in Go Playground, you will get the following output:

    An error has occurred:  <nil>
    Type of err:  *main.MyTestError

    The reason why this happens should now be apparent by now: to return the error, Go copied the value of err (of type *MyTestError) to a variable of type error: exactly as we did in the previous example.
    We can quickly fix the code returning a naked nil:

    package main
    
    import (
    	"fmt"
    	"reflect"
    )
    
    type MyTestError struct {
    }
    
    func (MyTestError) Error() string {
    	return "Test Error String"
    }
    
    func MyTestFunc() error {
    	var err *MyTestError
    	err = err  // let's do something with the variable to avoid compiling error
    	return nil
    }
    
    func main() {
    	err := MyTestFunc()
    	if err != nil {
    		fmt.Println("An error has occurred: ", err)
    		fmt.Println("Type of err: ", reflect.TypeOf(err))
    		return
    	}
    	fmt.Println("Success!")
    }

    Running the code in the Go Playground we now get the following output:

    Success!

    Three cases to keep in mind

    Reusing error variables and returning custom error structures is a widespread practice, and there isn't anything wrong with that. However, you should keep the form of the returned error in mind when checking it for a nil value:

    1. If you control the source code of the called function, ensure it returns an error interface and always returns a naked nil value.

    2. If the function you call returns a concrete object, use a dedicated variable to store that function error.

    3. In all the other cases, if you see weird behaviour where Go says that a nil variable is not nil, you can always use the reflect package to check the value specifically:

      reflect.ValueOf(err).IsNil()

    Summary

    I hope this has expanded your knowledge of the Go language. Please leave a comment below if you have questions about this article. As always, we welcome your feedback.

    Related Posts

    • Using Delve to debug Go programs on Red Hat Enterprise Linux

    • Troubleshooting and FAQ: Red Hat Enterprise Linux

    • Build your own RPM package with a sample Go program

    Recent Posts

    • How to enable Ansible Lightspeed intelligent assistant

    • Why some agentic AI developers are moving code from Python to Rust

    • Confidential VMs: The core of confidential containers

    • Benchmarking with GuideLLM in air-gapped OpenShift clusters

    • Run Qwen3-Next on vLLM with Red Hat AI: A step-by-step guide

    What’s up next?

    Path to GitOps cover card

    Read The Path to GitOps for a comprehensive look at the tools, workflows, and structures teams need to have in place in order to enable a complete GitOps workflow.

    Get the e-book
    Red Hat Developers logo LinkedIn YouTube Twitter Facebook

    Products

    • Red Hat Enterprise Linux
    • Red Hat OpenShift
    • Red Hat Ansible Automation Platform

    Build

    • Developer Sandbox
    • Developer Tools
    • Interactive Tutorials
    • API Catalog

    Quicklinks

    • Learning Resources
    • E-books
    • Cheat Sheets
    • Blog
    • Events
    • Newsletter

    Communicate

    • About us
    • Contact sales
    • Find a partner
    • Report a website issue
    • Site Status Dashboard
    • Report a security problem

    RED HAT DEVELOPER

    Build here. Go anywhere.

    We serve the builders. The problem solvers who create careers with code.

    Join us if you’re a developer, software engineer, web designer, front-end designer, UX designer, computer scientist, architect, tester, product manager, project manager or team lead.

    Sign me up

    Red Hat legal and privacy links

    • About Red Hat
    • Jobs
    • Events
    • Locations
    • Contact Red Hat
    • Red Hat Blog
    • Inclusion at Red Hat
    • Cool Stuff Store
    • Red Hat Summit
    © 2025 Red Hat

    Red Hat legal and privacy links

    • Privacy statement
    • Terms of use
    • All policies and guidelines
    • Digital accessibility

    Report a website issue