Go about Interface's understanding (ii)

Source: Internet
Author: User
This is a creation in Article, where the information may have evolved or changed.

One of the details about a type holding a method is:
For a named specific type T, some of its methods are recipients of the type T itself while others are pointers to T. It is legal to raise a *t method on a parameter of type T, as long as this argument is a variable
This is just a syntactic sugar, and the compiler implicitly acquires its address. However, the value of the T-type does not have a method of *t pointers, for example:

type IntSet struct { /* ... */ }func (*IntSet) String() stringvar _ = IntSet{}.String()  // compile error: String requires *IntSet receiver/* 但是我们可以再一个IntSet值上调用这个方法: */var s IntSetvar _ = s.String()  // OK: s is a variable and &s has a String method/* 然而,由于只有*IntSet类型有String方法,所以也只有*IntSet类型实现了fmt.Stringer接口 */var _ fmt.Stringer = &svar _ fmt.Stringer = s // compile error: IntSet lacks String method

Just as envelopes encapsulate and hide letters, the interface type encapsulates and hides the concrete type and its value. Even if the specific type has other methods, only the method exposed by the interface type is called to:

os.Stdout.Write([]byte("hello")) // OK: *os.File has Write methodos.Stdout.Close()                // OK: *os.File has Close methodvar w io.Writerw = os.Stdoutw.Write([]byte("hello"))         // OK: io.Writer has Write methodw.Close()                        

With respect to interfaces with fewer methods, the interface type of more methods will tell us more about the information it holds, and the requirements for implementing its classes are stricter. As for interface{}, which is called an empty interface type, an empty interface type has no requirement to implement its type, so any value can be assigned to an empty interface type.

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.