Avoiding the go language from the design interface{} = Nil Judgment error-prone simple method

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

The interface{} of the go language is essentially a structure that contains a type field and a pointer field.

Many beginners compare the interface{} with nil, which has been given the type in some cases, and are surprised to find that they are not equal.

In fact, from the design, we can easily avoid this problem, that is, the use of Go function multiple return value characteristics, after the general return value to add an OK bool type return value, can be.

When used, it is only a matter of determining whether the last return value OK is equal to true, and perfectly avoids the hassle of getting into X's potentially typed information.

Students who have doubts about this can compare the following two scenarios:

It is because any pointer assigned to interface{}, the Type information field of interface{} will be filled, so it is not equal to nil. Let's look at the following example:

The variable t is a null pointer, after assigning to I, I is not equal to nil.

For a clear and readable code, I recommend using the function return value design recommended at the beginning of this article to circumvent the pitfalls described in this 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.