Golang return &errorstring, not errorstring reason

Source: Internet
Author: User
This is a created article in which the information may have evolved or changed.

Errors Bag

Check out the Golang errors package and you'll find its source code:

func New(text string) error {return &errorString{text}}// errorString is a trivial implementation of error.type errorString struct {s string}func (e *errorString) Error() string {return e.s}

A pointer to the ErrorString type that implements the error interface is returned. Then why not return the value type of errorstring??

You may say: Because only ' *errorstring ' has the ' Error ' method ...

Wrong, and the wrong mistake.

Positive solution:

We are calling errors. New ("") to return an error, you can compare the pointer to compare the error equality, actually control the same error we only create an Error object. Otherwise the object is copied and the comparison is false.

And the pointer will be compared to nil, if the string "" Although the error content is empty, but there are errors.

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.