Senior
What is an error in Go? How to handle errors?
sobes.tech AI
Answer from AI
In Go, error is a built-in interface that represents an error as a value with an Error() string method. Error handling in Go is based on explicit checking of the error return value after calling a function. Instead of exceptions, a pattern is used where a function returns a result and an error, and the calling code checks whether the error is nil.
Example of error handling:
package main
import (
"errors"
"fmt"
)
func divide(a, b float64) (float64, error) {
if b == 0 {
return 0, errors.New("division by zero")
}
return a / b, nil
}
func main() {
result, err := divide(10, 0)
if err != nil {
fmt.Println("Error:", err)
return
}
fmt.Println("Result:", result)
}
This approach makes errors explicit and allows flexible handling.