Golang Error packet usage and error type principle

Source: Internet
Author: User
Tags builtin
This is a creation in Article, where the information may have evolved or changed.
Package Mainimport ("Errors" "FMT") func F1 (code int) (int, error) {if code = = 1 {return-1, errors. New ("MSG test error")}return code, nil}type msgerror struct {code intmsg string}func f2 (code int) (int, error) {if code = = 1 {return-1, &msgerror{code, "struct MSG test Error"}}return code, Nil}//golang built-in error for interface type/* is defined as type err or interface {Error () string} can be found in the built-in package corresponding to the source code goroot/src/builtin/builtin.go specific How a situation does not understand. But look at the corresponding error in the package, the new method returns a corresponding constructor pointer and defines an error method guess should be if the return is the error type inside will automatically call the corresponding data type error method and so really understand again to modify the article * * Func (msg *msgerror) Error () string {return FMT. Sprintf ("%s", Msg. MSG)}func Main () {//for _, V: = range []int{1, 2, 3, 4, 5, 6} {//if code, ERR: = F1 (v); Err! = nil {//fmt. PRINTLN (ERR)//} else {//fmt. Println ("Success:", code)//}//}for _, I: = range []int{1, 2, 3} {if code, ERR: = F2 (i); Err! = Nil {fmt. Println (EXRR)} else {fmt. Println ("Success:", Code)}}

Related Article

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.