Errors _ Golang

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.