In Go it's idiomatic to communicate errors via an explicit, separate return value. This constrasts errors via an explicit, separate return value. This constrasts with the exceptions used in languages like Java and Ruby and the overloaded single Result/error value so Metimes used in C. Go ' s approach makes it easy-to-see which functions return errors and to handle them using the same language constructs EMP Loyed for any other, non-error tasks
Package Mainimport ("Errors" "FMT") Func F1 (Argint) (int, error) { ifarg = = the { return-1, errors. New ("can ' t work with") } returnArg +3, Nil}type argerrorstruct{argintprobstring}func (E*argerror) Error ()string { returnFmt. Sprintf ("%d-%s", E.arg, E.prob)} Func F2 (Argint) (int, error) { ifarg = = the { return-1, &argerror{arg,"can ' t work with it"} } returnArg +3, Nil}func Main () { for_, I: = range []int{7, the} { ifR, E: = F1 (i); E! =Nil {fmt. Println ("F1 failed:", E)} Else{fmt. Println ("F2 worked:", R)} } for_, I: = range []int{7, the} { ifR, E: = F2 (i); E! =Nil {fmt. Println ("F2 failed:", E)} Else{fmt. Println ("F2 worked:", R)} } _, E:= F2 ( the) ifAE, OK: = E. (*argerror); OK {fmt. Println (Ae.arg) fmt. Println (Ae.prob)}}
F2 worked: F1 failed: can'twork with F2 worked: C12>f2 failed: the Can'twork with it can' /c19>t work with it
Summarize:
The 1:golang built-in function builtin.go inside defines the type error interface{error () string}; The implementation of this method is a custom Error (view Source COMMAND + SHIFT + left mouse button)
2: ....
Errors _ Golang