==Every type has an interface, which is the set of methods defined for that type.==

Go’s interfaces let you use duck typing

  • This is not pure duck typing, because when possible the Go compiler will statically check whether the type implements the interface.
  • Like you would in a purely dynamic language like Python but still have the compiler catch obvious mistakes like passing an int where an object with a Readmethod was expected, or like calling the Readmethod with the wrong number of arguments.

This bit of code defines a struct type Swith one field, and defines two methods for S.

type S struct { i int }
func (p *S) Get() int { return p.i }
func (p *S) Put(v int) { p.i = v }

You can also define an interface type, which is simply a set of methods. This defines an interface I with two methods:

type I interface {
  Get() int;
  Put(int);
}

Sis a valid implementation for I, because it defines the two methods which Irequires. Note that this is true even though there is no explicit declaration that ==S==implements ==I==.

For every type which is converted to an interface type, gccgo will build a type descriptor. Type descriptors are used by the type reflection support in the reflect package, and they are also used by the internal runtime support.

For each type, a type descriptors defines a (possibly empty) list of methods.

For each method five pieces of information are stored:

  1. a hash code for the type of the method (i.e., the parameter and result types)
  2. the name of the method
  3. for a method which is not exported, the name of the package in which it is defined
  4. the type descriptor for the type of the method
  5. a pointer to the function which implements the method

https://www.henrydu.com/2021/02/07/golang-interface-brief-look/

In gccgo, an interface value is really a struct with three (the first struct member concats more than one field) fields:

libgo/runtime/interface.h

struct __go_interface
{
  /* A pointer to the interface method table.  The first pointer is
     the type descriptor of the object.  Subsequent pointers are
     pointers to functions.  This is effectively the vtable for this
     interface.  The function pointers are in the same order as the
     list in the internal representation of the interface, which sorts
     them by name.  */
  const void **__methods;
 
  /* The object.  If the object is a pointer--if the type descriptor
     code is GO_PTR or GO_UNSAFE_POINTER--then this field is the value
     of the object itself.  Otherwise this is a pointer to memory
     which holds the value.  */
  void *__object;
};

https://research.swtch.com/interfaces

https://www.airs.com/blog/archives/277


🌱 Back to Garden