Golang errors.Is() function is “used to check if an error matches a specific target error.” This function helps with error comparisons by determining if the given error is equal to, or wraps, the target error.
Syntax
func Is(err, target error) bool
Parameters
- err: The tree consists of err itself, followed by the errors obtained by repeatedly calling Unwrap. When err wraps multiple errors, Is examines err followed by a depth-first traversal of its children.
- error: An error is considered to match a target if it is equal to that target or if it implements a method Is(error) bool such that Is(target) returns true.
Return value
It returns a boolean value, which is true if the err is equal to the target error or if the err wraps the target error. Otherwise, it returns false.
Example
package main
import (
"errors"
"fmt"
"io"
"os"
)
func main() {
_, err := os.Open("notavailable.txt")
if err != nil {
if errors.Is(err, os.ErrNotExist) {
fmt.Println("The file does not exist.")
} else if errors.Is(err, io.ErrUnexpectedEOF) {
fmt.Println("Unexpected EOF encountered.")
} else {
fmt.Println("An unknown error occurred:", err)
}
}
}
Output
The file does not exist.
That’s it.

Krunal Lathiya is a seasoned Computer Science expert with over eight years in the tech industry. He boasts deep knowledge in Data Science and Machine Learning. Versed in Python, JavaScript, PHP, R, and Golang. Skilled in frameworks like Angular and React and platforms such as Node.js. His expertise spans both front-end and back-end development. His proficiency in the Python language stands as a testament to his versatility and commitment to the craft.