Error
This Go program demonstrates how to use errors in Go and introduces a custom error type. It defines two functions, f1
and f2
, both of which return an int
and an error
.
The f2
function introduces a custom error type argError
. The main
function then calls these functions and handles the errors.
Output
Explanation:
The
f1
function returns either the result ofarg + 3
or an error ifarg
is equal to 42. It uses the standarderrors.New
function to create a simple error.The
argError
type is a custom error type with fieldsarg
andprob
. It has anError
method to implement theerror
interface.The
f2
function returns either the result ofarg + 3
or a customargError
ifarg
is equal to 42.The
main
function demonstrates the usage of these functions:Calls to
f1
andf2
are made in loops, and errors are handled using conditional statements.For the custom error type
argError
, type assertion is used to access its fields.
This example illustrates how to work with errors in Go, including creating custom error types and handling errors returned by functions.
Last updated
Was this helpful?