The error interface type is introduced in Golang as the standard mode for fault handling, and if the function returns an error, the return value type list must contain error. The error process is similar to the code in the C language, and can be returned on a level-by-layer basis until it is processed.
Basic usage of error
The error type is actually an error interface that abstracts the error () method, and Golang uses that interface for standard error handling.
The error corresponds to the source code as follows:
Type Error Interface {
Error () string
}
This design also embodies the "orthogonal" concept in Go philosophy: the separation of error context from the type of error. Regardless of whether the error context is int, float, or string or whatever, use error as the return value type.
In general, if the function needs to return an error, it will be the last of multiple return values (but this is not a mandatory requirement).
Let's use a simple function to demonstrate the use of error in the Go language:
Func Sqrt (f float64) (Float64, error) {
If f < 0 {
Return-1, errors. New ("Math:square root of negative number")
}
return Math. Sqrt (f), nil
}
Func Main () {
result, err:= Sqrt (-13)
If err! = Nil {
Fmt. PRINTLN (ERR)
} else {
Fmt. PRINTLN (Result)
}
}
Here's how to use the error: Use errors. New can return an error message. Compared to other language anomalies, the Golang method is relatively easier and more intuitive.
Error Advanced Usage
Except for the errors above. New usage, we can also implement the error interface, implement the error () method by itself, to achieve the error output of the custom parameter.
Type dualerror struct {
Num float64
&NBSP;&NBSP;&N Bsp; problem string
}
Func (e dualerror) Error () string {
return fmt. Sprintf ("wrong!!!, because \"%f\ "is a negative number", E.num)
}
Func Sqrt (f float64) (Float64, error) {
If f < 0 {
return-1, dualerror{num:f}
}< /p>
return math. Sqrt (f), nil
}
Func main () {
result, err:= Sqrt ( -13)
&N Bsp If err! = nil {
FMT. PRINTLN (Err)
}else{
FMT. PRINTLN (Result)
}
}