This is the sixth day of my participation in Gwen Challenge

Why doesn’t the type implement the Equal interface?

Let’s look at an example where a type is comparing itself

// Define an interface
type Equaler interface {
    Equal(Equaler) bool
}

/ / implement it
type T int
func (t T) Equal(u T) bool { return t == u } // does not satisfy Equaler
Copy the code

Unlike other implementations of polymorphic systems, T does not implement Equaler in the above example because t.eq () takes arguments of type T, not the literal Equaler type required. You haven’t implemented find yet, and you want to use an interface instead of yourself? It’s impossible.)

In GO, the type system does not optimize the Equal argument because it is the programmer’s responsibility. See the following example of T2, which implements the Equaler method correctly.

type T2 int
func (t T2) Equal(u Equaler) bool { return t == u.(T2) }  // satisfies Equaler
Copy the code

This is different from the type systems of other languages, because in Go, any type that satisfies the Equaler interface is passed as an argument to T2.equal. At runtime, we need to check whether the argument satisfies T2, which some languages do at compile time.

The polymorphic figures illustrate as illustrateCopy the code

A relevant example is as follows:

type Opener interface {
   Open() Reader
}

func (t T3) Open(a) *os.File
Copy the code

In Go, T3 does not implement Opener, but it may be implemented in other languages.

While Go’s type system does less to support this, it also makes implementing the interface less restrictive, making it easier to declare, because you only have to worry about one thing: Are the names and signatures of functions really the same as those defined for that interface? We believe that the benefits of this outweigh the benefits of auto-optimized type matching.

Will Go be organized in some kind of polymorphic language in the future? We hope that if there is one, it must be able to express the meaning of the above example and be statically checked for problems.