Junior — Middle
Can you explain what the Error type in Go language is and how it is used for error handling?
sobes.tech AI
Answer from AI
In the Go language, the error type is a built-in interface used for error handling. It is defined as:
type error interface {
Error() string
}
This means that any type implementing the Error() string method is considered an error.
Usage:
- Functions that may end with an error usually return a value of type
erroralong with the result. - If there is no error,
nilis returned. - Error checking is done using the condition
if err != nil.
Example:
func divide(a, b float64) (float64, error) {
if b == 0 {
return 0, fmt.Errorf("division by zero")
}
return a / b, nil
}
result, err := divide(10, 0)
if err != nil {
fmt.Println("Error:", err)
} else {
fmt.Println("Result:", result)
}
Thus, error in Go is the standard way to pass and handle errors in a program.